angular [(ngModel)] 在 *ngFor 中

angular [(ngModel)] inside *ngFor

怎么添加用户后所有输入框都绑定了?

https://stackblitz.com/edit/angular-4e65ne

我将它们分配给数组中的不同元素。

好吧,您在数组的每个位置都分配了相同的 NewUser 对象。您必须在方法末尾使用空对象初始化变量 this.user

 addUser(){
   _.assign(this.user[this.userCount], <NewUser>{
   userId: 'userId1',
   reason: 'reason1'
   });

 this.user1[this.userCount] = this.user;
 this.userCount++;
 this.user = <NewUser>{}; // Here you have to reset the variable
}

您多次将同一个用户对象添加到数组中。也不必要的复杂,你可以简化成这样:

您可以将 AppComponent 减少到

import { Component } from '@angular/core';
import { NewUser } from './user.model';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  name = 'Angular';
  public user1 = Array<NewUser>();

  addUser() {
    this.user1.push(<NewUser>{
      userId: 'userId1',
      reason: 'reason1'
    });
  }
}

那么您的绑定工作正常:

<div class="input-group-prepend">
    <span class="input-group-text addUser" (click)="addUser()">+ User</span>
</div>

<div *ngFor="let i of user1; let index = index"> 
  <div class="input-group mb-3" >

    <div class="input-group-prepend">
    <span class="input-group-text" id="basic-addon1">User Id</span>
    </div>
    <input type="text" class="form-control" name="userid-{{index}}" [(ngModel)]="user1[index].userId"> {{index}}
    <div class="input-group-prepend">
      <span class="input-group-text" id="basic-addon1">Reason</span>
    </div>
      <input type="text" class="form-control" name="reason-{{index}}" [(ngModel)]="user1[index].reason">

    <div class="input-group-prepend">
      <span class="input-group-text" id="basic-addon1" (click)="removeUserId(index)"><i class="fa fa-trash" aria-hidden="true"></i></span>
    </div>
  </div>
</div>

Stackblitz:https://stackblitz.com/edit/angular-bamrwa?file=src%2Fapp%2Fapp.component.ts

您只需将新对象添加到 array:

addUser(){
       this.user1.push({userId:'', reason:''});
    }