Angular 2 父子组件数据通信
如今的前端开发,都朝组件式开发模式靠拢,如果使用目前最流行的前端框架Angular和React开发应用,不可避免地需要开发组件,也就意味着我们需要考虑组件间的数据传递等问题,不过Angular 2已经为我们提供了很好的解决方案。 父组件和子组件接触过面向对象编程的开发者肯定不会对父子关系陌生,在Angular 2中子组件存在于父组件“体内”,并且父子组件可以通过一些渠道进行通讯。 父组件向子组件传入数据 – @Input当我们着手开始开发一个组件时,第一件想到的应该就是为其传入数据,毕竟我们期望组件为我们处理某些工作通常就需要给其提供“养料”,毕竟不能又让马儿跑,又不给马儿吃草。Angular 2中子组件使用装饰器 // child-component.ts
import { OnInit,Component,Input } from '@angular/core';
@Component({
selector: 'child-component',...
})
export class ChildComponent implements OnInit {
@Input
count: number = 0;
ngOnInit() {
console.log(this.count); // 父组件内传入的值或者我们自己设置的初始值0
}
increaseNumber() {
this.count ++;
}
descreaseNumber() {
this.count --;
}
}
可以看到,我们使用装饰器 // father-component.ts
import { Component } from '@angular/core';
import { ChildComponent } from '../child-component/child-component';
@Component({
template: `
<child-component [count]='initialCount'></child-component> `,... }) export class FatherComponent { initialCount: number = 5; }
父组件使用 子组件通知父组件数据已处理完成 – @Output、EventEmitter父组件传入数据给子组件之后并不是万事大吉了,就像父母养育孩子,供其读书,但孩子需要把学习进度、考试成绩等呈现给父母看(不管是否自愿…),父组件也需要子组件在合适的时机通知自己数据已经处理好,可以检阅了。而此时就需要使用@Output和EventEmitter了。 // father-component.ts
import { Component } from '@angular/core';
import { ChildComponent } from '../child-component/child-component';
@Component({
template: `
<child-component [count]='initialCount' (change)="countChange($event)"></child-component> `,... }) export class FatherComponent { initialCount: number = 5; countChange($event) { } }
看看我们在父组件中加入了什么东东: 1. 2.增加了 但是稍等,当我们为input标签指定type、placeholder等属性时,我们知道它们都已经被“实现了”,所谓“实现”,即这些属性在input标签上是有意义的。但是目前这里我们为 // child-component.ts
import { Component,Input,Output,EventEmitter } from '@angular/core';
@Component({
selector: 'child-component',...
})
export class ChildComponent {
@Input
count: number = 0;
@Output
change = new EventEmitter();
increaseNumber() {
this.count ++;
this.change.emit(this.count);
}
descreaseNumber() {
this.count --;
this.change.emit(this.count);
}
}
让我们再来看看在子组件中增加了什么东东: 1.使用装饰器@Output修饰了 2.在 此时,我们在 // father-component.ts
...
countChange($event) {
this.initialCount = $event;
}
...
总结不知道你有没有发现,其实上面我们模拟了“双向数据绑定”:父组件将数据传入子组件,子组件改变数据时通知父组件进行“同步更新”。但是要注意其实数据流向是单向的,即数据是父组件单向流入子组件,父组件数据的更新是通过子组件的事件通知以后才被更新。也就是说其实在Angular 2中:双向数据绑定 = 单向数据绑定 + 事件,以我们最熟悉的 <input type='text' name='userName' [(ngModel)]="userName">
和下面的写法是等价的: <input type='text' name='userName' [ngModel]="userName" (ngModelChange)="userName=$event">
同样的,如果将我们的 <child-component [(count)]='initialCount'></child-component>
参考文档
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |