组件通信及两个或者多个组件之间共享信息的方法;
组件之间通信分为以下几种情况:
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: