标签: change-detector-ref

尽管我调用了 ChangeDetectorRef.detectChanges,但未触发 ngOnChanges

export class AppComponent implements OnInit, OnChanges {
  @Input()
  value: number;

  constructor(
    private cdr: ChangeDetectorRef
  ) {}

  ngOnInit() {
    of(1).subscribe(v => {
        this.value = v;

        console.log(1);

        this.cdr.detectChanges();

        of(2).subscribe(() => {
          console.log(2);
        });
      })
  }

  ngOnChanges(c: SimpleChanges) {
    console.log(3);
  }
}
Run Code Online (Sandbox Code Playgroud)

我希望 console.log 的序列应该是1, 3, 2但它只打印1, 2.

我知道ngOnChanges只有在input模板绑定发生更改时才会触发。

所以我this.cdr.detectChanges()马上打电话,console.log(1)但没有奏效。

这里有什么问题?

我在这里制作了 stackblitz 示例 - https://stackblitz.com/edit/angular-ivy-ugdba1

额外问题

如果无法触发ngOnChanges组件内部,将触发哪些生命周期钩子this.cdr.detectChanges()

ngonchanges angular change-detector-ref

0
推荐指数
1
解决办法
428
查看次数

标签 统计

angular ×1

change-detector-ref ×1

ngonchanges ×1