I have a form that allows an employer to edit the information for their employees. In Angular, it's a template driven form, and we're using ngModel for two way data binding. On page load, we get the employee's information from the database, and then they can edit that. Pretty basic stuff. We've been doing this for a while, but are now adding in a confirmation step between their edits and saving to the database.
I decided to make it so that when going from the form to the list of differences for them to confirm, the edit form is hidden with *ngIf. If they want to go back and undo changes or make more changes, the form is shown again. Again, it's relatively basic stuff and it all happens in one main component (with multiple children components nested inside it).
The problem is that when going from the form to the confirmation step, and then back to editing, the employee model doesn't show the values in the inputs.
Here's the form on page load:
and here it is after going to the summary step and then back to the form
If I console.log the employee model when going back and forth between steps, I can see the correct information. But it doesn't show in the page in the inputs.
Any reasons why would be really helpful. I'm not sure what is causing it. I know there isn't a ton of detail here, but it's because I'm not sure what's causing it and it's not a complicated process. Hopefully there's enough here that someone can go off to point me in the right direction.
Here's the ngOnChanges function in the form component:
You can see I reset it to null, then set the employee variable to what's passed in to the component. Here's what those console.logs show:
But again, the template in the browser doesn't have the values in the input fields, nor does it show the values when outputting the employee variable in JSON with this: {{ employee | json }}.
Since there is no code, I can only guess from my experience. I believe you don't check ngOnChanges in your child component when you show the form again.
Try to do something like
ngOnChanges(changes: { [propKey: string]: SimpleChange }) {
if (changes.property) {
this.property = changes.property.currentValue;
// if changeDetection: ChangeDetectionStrategy.OnPush
this.ChangeDetectorRef.detectChanges()
}
}
So, turns out this was in the ngOnInit function:
this.employee = new EmployeeClass();
It must have been a hold over from early on in development. On page load it works fine, likely because the new instance is made and then after that the data comes back from the database. But in this case, when you come back a step and aren't reloading from the database, that ngOnInit function overrules the ngOnChanges. Or something along those lines...that's all I can assume is happening.