I'm trying to bind each item of an array to [(ngModel)] of a text box.
component.ts
arr:string[] = ["",""];
component.html [FIRST APPROACH]
<div class="row" *ngFor="let item of arr;">
<div class="col-12">
<input type="text" [(ngModel)]="item">
</div>
</div>
First Approach fires error, it was working fine in angular 7: Cannot use variable 'item' as the left-hand side of an assignment expression. Template variables are read-only.
component.html [SECOND APPROACH]
<div class="row" *ngFor="let item of arr; let i = index">
<div class="col-12">
<input type="text" [(ngModel)]="arr[i]">
</div>
</div>
Second approach works but the input:text box loss focus after typing a single letter.
Can somebody provide me a perfect approach for similar scenarios?
use trackby
in compoment :
trackByFn(index: any, item: any) {
return index;
}
in html :
<div class="row" *ngFor="let item of arr; let i = index ; trackBy:trackByFn">
<div class="col-12">
<input type="text" [(ngModel)]="arr[i]">
</div>
</div>
stackblitz link for demo : https://stackblitz.com/edit/angular-cwyrs9
Please let me know if it is not working
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With