0
我创建了一个plunker这里:角2双向组件绑定不调用父ngOnChange
http://plnkr.co/edit/8bwqkYQ6tqrpGwHT588y?p=preview
,显示问题。
基本上,我有2个组件。第一个组件具有属性与子组件的双向绑定。
我的父组件是:
import { Component, Input, Output, EventEmitter } from '@angular/core'
import { ChildComponent } from "./childComponent"
@Component({
selector: 'parentComponent',
template: `
<div>
<a href="#" (click)="selectedId = 0">Reset</a><br>
<div>Parent SelectedId: {{selectedId}}</div>
<childComponent [(selectedId)]="selectedId"></childComponent>
</div>
`,
directives: [ChildComponent]
})
export class ParentComponent {
@Input() selectedId: number;
ngOnChanges(changes) {
console.log("Parent changes called!");
}
}
和我的孩子组成:
import { Component, Input, Output, EventEmitter } from '@angular/core'
@Component({
selector: 'childComponent',
template: `
<div>
<div>Child SelectedId: {{selectedId}}</div>
</div>
`,
directives: []
})
export class ChildComponent {
@Input() selectedId: number;
@Output() selectedIdChange: EventEmitter<number> = new EventEmitter<number>();
constructor() {
setTimeout(() => {
this.selectedId = 100;
this.selectedIdChange.emit(this.selectedId);
}, 2000);
}
ngOnChanges(changes) {
console.log("Child changes called!");
}
}
在孩子,我设置了超时2秒后编程改变selectedId的值,然后发出价值回到父母。
这一切的伟大工程,除了一件事......父的ngOnChange才会被调用一次。
我会认为父母非常想知道孩子是否已经改变了值,否则2路绑定的意义何在?
我在这里错过了什么?
可我只是说这是真的,真的很愚蠢。什么时候你不想让你的父组件被通知,当你明确地将它设置为双向绑定时,属性发生了变化?它应该自动将变化事件向上冒泡。 – Scottie
@Scottie,好了,有时你只是想父(例如,父视图)进行更新,并且不需要通知,因为你并不需要当孩子做了更改执行任何逻辑。而且你是正确的,EventEmitter发出的事件不会冒泡。如果您希望通知多个组件发生单个更改,则推荐使用共享服务中的Observable或Subject。 –