简体   繁体   中英

Angular 5 ngModel ngFor not working with trackBy

This is my html

<div class="card">
  <div class="card-body" *ngFor="let bookInstance of bookInstanceList; trackBy: trackByBookList;">
     <label for="status">Status</label>
          <input type="text" class="form-control" id="status" placeholder="Status of the book" [(ngModel)]="bookInstance.status" name="status" required>
  </div>
</div>

This is my typescript

private bookInstanceList = [
      {
        "status": "Not Available",
      },
      {
        "status": "I am  Available",
      }
    ];

  trackByBookList(index: number, bookInstance: any): any {
    return index;
  }

I followed many tutorials on trackBy but i am still not able to get the input field of the first input to be "Not Available" and the 2nd one to be "Available". I think it is because i am using input tags? I am using angular 5

When using input fields in a form tag, make sure that each field has a unique name (except for a group of radio buttons, where the radio input elements share the same name):

<div *ngFor="let bookInstance of bookInstanceList; let i=index; trackBy: trackByBookList;">
    <label>Status
        <input type="text" [name]="'status_' + i" [(ngModel)]="bookInstance.status" ...>
    </label>
</div>

You may also consider removing the id attribute. Each id should be unique, which is not the case in your original code.

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