angularngonchanges

Detect change of SimpleChanges in ngOnChanges if Input with observable


In Angular, I usually use ngOnChanges to detect what was change from parent component.

But now, I got confuse when declare as following:

  @Input() data: Observable<Student>;

And in ngOnChanges method:

ngOnChanges(changes: SimpleChanges): void {
    if (changes.data?.currentValue) {
      // code here
    }
  }

In this code, I want to pass data (data get from API) from Parent to Child. In Child, I'll subscribe the data to bind to layout.

What I want here, when there is any change in Parent, the Child should listen and re-bind with new data to layout.

But with data is observable type, the code 'changes.data?.currentValue' can know when it changes?

Please advise


Solution

  • ngOnChanges will be called whenever Input values from the parent component change. In order to trigger a change when the Observable emits a new value, you’ll need to subscribe to the observable from the parent component and pass the emitted value to the child.

    This can be done as follows:

    Parent Component Template

    <child-component [data]=“(studentObservable$ | async)”></child-component>
    

    Child Component

    @Input() data: Student;