组件通信及两个或者多个组件之间共享信息的方法;
组件之间通信分为以下几种情况:
1、父组件向子组件传递数据;
2、 子组件向父组件传递数据;
3、非嵌套组件之间的通信;
下面将详细说明如何实现这几种通信
父组件向子组件传递数据:属性绑定方式([属性名])
子组件中通过@Input 装饰器自定义属性,父组件绑定这个属性。
子组件实现:
import { Component, OnInit,Input } from '@angular/core'; @Component({ selector: 'app-child', templateUrl: './child.component.html', styleUrls: ['./child.component.css'] }) export class ChildComponent implements OnInit { @Input() private data: any;//data名字根据引用场景自定义 constructor() { } ngOnInit() { } }
父组件实现:
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-parent', template: `<app-child [data]="dataToChild"></app-child>`, styleUrls: ['./parent.component.css'] }) export class ParentComponent implements OnInit { private dataToChild: string = ' I am parent'; constructor() { } ngOnInit() { } }
子组件向父组件传递数据:事件绑定 父组件监听子组件事件
子组件使用EventEmitter创建自定义事件,并且通过@Output()装饰器把它作为属性暴露出来,父组件通过绑定这个属性来监听事件从而获取子组件数据。
子组件实现:
import { Component, OnInit} from '@angular/core'; @Component({ selector: 'app-child'

本文详述了Angular2+中组件间的通信方式,包括父组件向子组件通过属性绑定传递数据,子组件通过事件发射器反馈信息,以及非嵌套组件间利用服务进行通信。还介绍了使用@ViewChild调用子组件方法以及子组件如何调用父组件方法的实现细节。
最低0.47元/天 解锁文章
37

被折叠的 条评论
为什么被折叠?



