NgFor shows empty objects after array.push
I have this in my template:
<input type="button" value="add" (click)="addEnvVar()"/> <div *ngFor="let envVar of application.env_vars"> <input type="text" name="key" [(ngModel)]="envVar.key"> <input type="text" name="value" [(ngModel)]="envVar.value"> </div> Code addEnvVar() : this.application.env_vars.push({key:'', value:''});
When the component is initialized, there is one object inside env_vars , and it is displayed just fine (the <input> fields are filled). After I click "add", I see in the console that there really are two objects in env_vars (the second is the "empty" object that I just added), and in the view there really are two <div> for each envVar , but all 4 <input> fields are empty .
What am I doing wrong?
UPDATE
I think the problem is that when ngFor creates more than one div , the inputs in each div all obtained by the same hard-coded name attribute (in my case, βkeyβ and βvalueβ), and the value is somehow related to this. I changed name="key" to name="key_{{i}}" ( i is a template variable containing the ngFor index ngFor ).
The question is, is that so? Or am I still missing something?
A culprit with such errors is most likely the default trackBy function that tracks links. Even if the data has not changed, but the links have changed, it will demolish the DOM and rebuild it, that is, all data inside the input fields will be cleared.
Component
trackBy(index) { return index } Template
*ngFor="let envVar of application.env_vars; trackBy: trackBy" Unfortunately, I canβt check it out without playback. However, JB Nizet's comment is right, and you should follow this advice; this is a task more suitable for reactive forms rather than template forms.