Angular 2 ngOnChanges 没有在快速变化的输入上触发

Angular 2 ngOnChanges not firing on rapidly changing input

我正在使用 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 生命周期挂钩只触发一次而不是 3 次,显示输入值从 0 变为 3。但是我需要在每次值更改时触发它 (0 -> 1 , 1 -> 2, 2 -> 3, 等等)。有办法做到这一点吗?

谢谢。

这是预期的行为。
Angular2 在 (click) 事件处理程序完成时运行更改检测,这是在第 3 个 += 1.
之后 当更改检测更新 @Input() 绑定时,将调用 ngOnChanges()