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

top*_*oon 0 ngonchanges angular change-detector-ref

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()

StP*_*lis 6

ngOnChanges 当从父组件更改输入参数时调用。

如果您想在任何检测后做某事,您应该使用 ngAfterViewChecked()