@H_4030@1. 组件通信
@H4030@我们知道Angular2应用程序实际上是有很多父子组价组成的组件树,因此,了解组件之间如何通信,特别是父子组件之间,对编写Angular2应用程序具有十分重要的意义,通常来讲,组件之间的交互方式主要有如下几种:
@H4030@l 使用输入型绑定,把数据从父组件传到子组件
@H403_0@l 通过 setter 拦截输入属性值的变化
@H_403_0@l 使用 ngOnChanges 拦截输入属性值的变化
@H_4030@l 父组件监听子组件的事件
@H4030@l 父组件与子组件通过本地变量互动
@H403_0@l 父组件调用 ViewChild
@H_4030@l 父组件和子组件通过服务来通讯
@H4030@本文会通过讲解着几种方式来对组件之间的通信做一个大致的介绍。
@H4030@
2. 输入型绑定
@H403_0@输入型绑定指的是利用模板语法中的属性型绑定方式,将父组件的数据传递到子组件对应的对象中,子组件中的对象一般使用@Input装饰器来修饰,作为数据的接受者,例如
<div class="jb51code">
<pre class="brush:js;">
@Component({
selector: 'child',template: 'I am fron {{input}}'
})
export class ChildComponent implements OnInit {
@Input()
input;
constructor() { }
ngOnInit() { }
}
@Component({
selector: 'parent',template: '<child [input]="data">'
})
export class ParentComponent implements OnInit {
data: string;
constructor() { }
ngOnInit() {
this.data = "parent";
}
}