ngOnChanges not triggered though I called ChangeDetectorRef.detectChanges

4.4k views Asked by At
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);
  }
}

I expected the sequences of the console.log should be 1, 3, 2 but it only prints 1, 2.

I know ngOnChanges will be only triggered when only input change comes from a template binding.

So I called this.cdr.detectChanges() right after console.log(1) but it didnt work.

What's the problem here?

I made stackblitz example here - https://stackblitz.com/edit/angular-ivy-ugdba1

Extra Question

If it's not possible to trigger the ngOnChanges inside the component, what lifecyle hooks will be triggered on this.cdr.detectChanges()?

2

There are 2 answers

6
StPaulis On BEST ANSWER

ngOnChanges is called when an Input Parameter is changed from your parent component.

If you want to do something after any detection you should use ngAfterViewChecked()

2
Andrei On

this.cdr.detectChages() calls change detection on the current component template. that means if current component contains <child [data]="someData"></child> then its [data] input will be checked for changes. child.ngDoCheck() will be called and if someData is new value child.ngOnChanges(...) will be called.