When using *ngFor in Angular to loop over an array and generate input text elements bound to the values in the array, I'm encountering some issues. The value is not binding correctly when a user inputs something into the text field.
I attempted to run changeDetection after updating the array but it did not resolve the problem.
In the code example below, I am dynamically generating input elements by clicking on an add button using an array of string values "test". The [ngModel] of the input is supposed to bind to the value inside the array, so all inputs should have the value "test".
However, when entering a value into the input field and then clicking on the add button, the generated input does not bind to the value in the array.
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
template: `
<button (click)="onAdd()">Add</button>
<br/><br/>
<input
*ngFor="let d of data;let i = index;trackBy:trackByfn"
type="text"
[ngModel]="data[i]"
>
<br/><br/>
data: {{data|json}}
`,
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
data = ['test'];
onAdd() {
this.data.push('test');
}
trackByfn = (index) => index;
}