简体   繁体   中英

how to use 2-way binding in angular 9

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM