【问题标题】:Angular 2 ngOnChanges not firing on rapidly changing inputAngular 2 ngOnChanges 不会在快速变化的输入上触发
【发布时间】:2017-07-02 23:00:13
【问题描述】:

我正在使用 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 等)。有没有办法做到这一点?

谢谢。

【问题讨论】:

    标签: angular angular2-template ngonchanges


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2018-06-21
      • 2017-11-29
      • 2018-01-20
      • 2016-04-06
      • 1970-01-01
      • 1970-01-01
      • 2019-04-21
      • 1970-01-01
      • 2018-10-22
      相关资源
      最近更新 更多