我正在尝试在我的两个组件(父组件和子组件)之间使用双向绑定,并尝试在两个组件的 ngOnChanges 中检测由此引起的更改。我可以通过更改父组件(应用程序组件)的输入/输出属性来触发子组件(测试组件)的 ngOnChanges。但是,我无法通过更改子组件中的双向绑定属性来触发父组件的 ngOnChanges。
可以在这里找到工作 Plunker:https ://plnkr.co/edit/AGh6EM9l9ENMufb9JWPW?p=preview
import { Component, OnInit, OnChange, Output, Input, EventEmitter } from '@angular/core';
@Component({
selector: 'my-app',
template: `<h1>Hello {{name}}</h1>
<h3>Two Way Parent - {{twoWaySend}} </h3>
<button (click) = "oneWayButtonPressed()">Increase oneWay from Parent</button>
<button (click) = "twoWayButtonPressed()">Increase TwoWay from Parent</button>
<test-component [oneWayReceive] = 'oneWaySend'
[(twoWayReceive)] = 'twoWaySend'></test-component>`
})
export class AppComponent implements OnChanges{
name = 'Angular';
oneWaySend = "You shall pass";
twoWaySend = "You shall both ways";
counter:int = 0;
negativeCounter:int = 0;
oneWayButtonPressed() {
this.oneWaySend = `${this.oneWaySend} ${++this.counter}`;
}
twoWayButtonPressed() {
this.twoWaySend = `${this.twoWaySend} ${--this.negativeCounter}`;
}
ngOnChanges() {
console.log('ngOnchange Parent ' + this.twoWaySend);
}
}
@Component({
selector: 'test-component',
template: `<h1>TestComponent {{name}} {{oneWayReceive}}</h1>
<h3>Two Way Child - {{twoWayReceive}}</h3>
<button (click) = "twoWayButtonPressed()">Change Two Way from Child</button>`
})
export class TestComponent implements OnChange {
@Input() oneWayReceive;
@Input() twoWayReceive;
@Output() twoWayReceiveChange: EventEmitter<string> = new EventEmitter<string>();
name = 'Angular';
negativeCounter = 0;
ngOnChanges() {
console.log(`OneWayReceive ${this.oneWayReceive} TwoWayReceive ${this.twoWayReceive}`);
}
twoWayButtonPressed() {
this.twoWayReceive = `${--this.negativeCounter} ${this.twoWayReceive}`;
this.twoWayReceiveChange.emit(this.twoWayReceive);
}
}