简体   繁体   中英

Angular NGRX / Reactive Form and ngOnChanges timing issue

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.

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

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

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

how to stop ngOnChanges Called before ngOnInit()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM