Angular NGRX / Reactive Form and ngOnChanges timing issue

487 Views Asked by At

Angular 9

I'm trying to use ngOnchanges to trigger the load to my form. The data for the form is coming from an @input from the shell-component.

The problem I have is ngOnChanges is firing BEFORE ngOnit and the form has not been built yet for the data to populate.

Playing around with it I have put in a temporary fix with a setTimeout, but its not ideal

ngOnChanges(changes: SimpleChanges): void {
 setTimeout(() => {
    // patch form with value from the store
    if (changes.profile) {
      const profile: IProfile = changes.profile.currentValue;
      this.displayProfile(profile);
    }
  }, 0);
}

The timeout even with 0 delay is enough for the form to catch up. If I don't put in the delay the data is loaded before the form is built and triggers an error with no data.

This seems pretty fundamental. what I am missing?

thanks.

2

There are 2 best solutions below

0
On

You can achieve it with a setter on the @Input() without needing ngOnChanges:

@Input()
set profile(profile) {
  this.displayProfile(profile);
}
3
On

You could use one of these very useful patterns described in answer below:

how to stop ngOnChanges Called before ngOnInit()