- 通过输入型绑定把数据从父组件传到子组件
@Input() hero: Hero;
改进:通过 setter 截听输入属性值的变化
父组件:
<app-name-child *ngFor="let name of names" [name]="name"></app-name-child>
子组件:
private _name = '';
@Input()
set name(value) {
this._name = (value && value.trim()) || 'no-name';
}
get name() {
return this._name;
}
改进:通过ngOnChanges()来截听输入属性值的变化。
当需要监视多个、交互式输入属性的时候,本方法比用属性的 setter 更合适。
监控多个输入属性的时候:
ngOnChanges(changes: SimpleChanges) {
// changes.prop contains the old and the new value...
}
父组件监听子组件的事件
- @Output()
@Output() voted = new EventEmitter<boolean>();
this.voted.emit('true');
<app-voter *ngFor="let voter of voters"
[name]="voter"
(voted)="onVoted($event)">
</app-voter>
- 父组件与子组件通过本地变量互动
父组件不能使用数据绑定来读取子组件的属性或调用子组件的方法。但可以在父组件模板里,新建一个本地变量来代表子组件,然后利用这个变量来读取子组件的属性和调用子组件的方法,如下例所示。
<button (click)="timer.start()">Start</button>
<button (click)="timer.stop()">Stop</button>
<div class="seconds">{{timer.seconds}}</div>
<app-countdown-timer #timer></app-countdown-timer>
父组件不能通过数据绑定使用子组件的 start 和 stop 方法,也不能访问子组件的 seconds 属性。
把本地变量(#timer)放到()标签中,用来代表子组件。这样父组件的模板就得到了子组件的引用,于是可以在父组件的模板中访问子组件的所有属性和方法。
- 父组件调用@ViewChild()
这个本地变量方法是个简单便利的方法。但是它也有局限性,因为父组件-子组件的连接必须全部在父组件的模板中进行。父组件本身的代码对子组件没有访问权。
@ViewChild(CountdownTimerComponent)
private timerComponent: CountdownTimerComponent;
// 方法:
start() { this.timerComponent.start(); }
stop() { this.timerComponent.stop(); }
// 属性:
<div class="seconds">{{ seconds() }}</div>
seconds() { return 0; }
ngAfterViewInit() {
// Redefine `seconds()` to get from the `CountdownTimerComponent.seconds` ...
// but wait a tick first to avoid one-time devMode
// unidirectional-data-flow-violation error
setTimeout(() => this.seconds = () => this.timerComponent.seconds, 0);
}
==>两种方法可以结合起来;模板中使用模板的时候使用#timer,如果是调用函数,或者js中使用属性的时候,可以使用 ViewChild!
父组件和子组件通过服务来通讯
// 服务:
private click1 = new Subject();
click1$ = this.click1.asObservable();
click1Fn(value) {
this.click1.next(value);
}
// 组件1:调用函数
add1() {
this.s1.click1Fn(1);
}
// 组件2中,声明订阅
ngOnInit() {
this.s2.click1$.subscribe((v) => {
console.log('2页面的订阅:', v);
});
}
或者使用:https://github.com/akveo/ngx-admin/releases?after=v2.0.0
v1.0中的订阅!global