ngOnChange only triggers after clicked somewhere on the screen after subscribe

780 Views Asked by At

I have the following components. Parent:

@Component({
  selector: 'test'
})

onAccountChange(account: AccountItem): void {
  this.appService.callApi.subscribe((data) => {
    this.availableInstrument = data
  })
}

And my Child component is as follows:

@Component({
  selector: 'child'
})
export class Child implements OnInit, OnChanges {

  @Input('availableInstrument') availableInstrument!: any[]

  ngOnChanges() :void {
      console.log("Change")
      this.initializeComponent()
  }

My question is at I notice that the ngOnChange function only gets called after I click somewhere else on the screen, even though the callback function (onAccountChange) has completed and availableInstrument has been populated from the api call. I would want the ngOnChange function be called as soon as the input data is changed from the api call rather than having to click somewhere else on the screen. If I hard code the input values in my call back function, I see ngOnChange is called immediately in the child component, but not when it is within the subscribe block.

Thank you so much!

1

There are 1 best solutions below

0
On

You need to set the change detection strategy to onPush.

@Component({
  selector: "child", 
 changeDetection: ChangeDetectionStrategy.OnPush
})