0

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.

Darren Street
  • 1,652
  • 17
  • 21

2 Answers2

2

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

@Input()
set profile(profile) {
  this.displayProfile(profile);
}
Gérôme Grignon
  • 3,859
  • 1
  • 6
  • 18
1

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

how to stop ngOnChanges Called before ngOnInit()

Oana
  • 135
  • 1
  • 6
  • The bool solution didn't work for me. SimpleChanges with isFirstChange either. Frankly setting a SetTimeout is cleaner than the hassle of a new subject. – Darren Street May 18 '21 at 08:02
  • Well... try the others, especially: the SimpleChanges API one: `!changes["bar"].isFirstChange()` – Oana May 18 '21 at 08:05
  • My point is that this is pretty fundamental, but it requires fiddling. I went through the documentation and couldn't find a unified approach. – Darren Street May 18 '21 at 08:07