* ngFor内的[[ngModel)]角

时间:2019-02-28 16:08:35

标签: javascript angular ngfor ngmodel

在尝试添加用户后,如何绑定所有输入框?

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

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

3 个答案:

答案 0 :(得分:1)

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

您可以将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

答案 1 :(得分:0)

好吧,您要在数组的每个位置分配相同的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
}

答案 2 :(得分:0)

您只需将新对象添加到array

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