我正在使用 Angular 2 @Input 属性将所需的数值传递给子组件,就像这样。
父组件:
@Component({
selector: 'test-parent',
template: '<button (click)="raiseCounter()">Click me!</button><test-child [value]="counter"></test-child>'
})
export class ParentComponent {
public counter: number = 0;
raiseCouner() {
this.counter += 1;
this.counter += 1;
this.counter += 1;
}
}
子组件:
@Component({
selector: 'test-child'
});
export class ChildComponent implments OnChanges {
@Input() value: number = 0;
ngOnChanges() {
if (this.value) {
this.doSomeWork();
}
}
doSomeWork() {
console.log(this.value);
}
}
在这种情况下,OnChanges 生命周期 Hook 只触发一次而不是 3 次,表明输入值从 0 变为 3。但是我需要在每次值更改时触发它 (0 -> 1, 1 -> 2、2 -> 3 等)。有办法做到这一点吗?
谢谢。
最佳答案
这是预期的行为。
Angular2 在 (click)
事件处理程序完成时运行更改检测,这是在第 3 个 += 1
之后。
当更改检测更新 @Input()
绑定(bind)时,将调用 ngOnChanges()
。
关于Angular 2 ngOnChanges 没有触发快速变化的输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42229805/