Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use 2-way binding in angular 9

Tags:

html

angular

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?

like image 351
Jauhar xlr Avatar asked Mar 31 '20 07:03

Jauhar xlr


Video Answer


1 Answers

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

like image 50
Sayooj V R Avatar answered Sep 29 '22 02:09

Sayooj V R