Angular 6重用形式具有不同的[[ngModel)]作为输入

时间:2018-10-18 20:04:17

标签: javascript html angular typescript

我想知道做这种事情的最好方法是什么,我有这种形式:

 <div class="telefono">
      <label>Telefonos</label>
      <div class="tel" *ngFor="let t of tfonos">
        <div class="row">
          <div class="col-md-2">
            <label for="tfijo">Telefono fijo</label>
            <input type="text" class="form-control" [(ngModel)]="telefono.telFijo" name="tfijo">
          </div>
          <div class="col-md-2">
            <label for="tcel">Telefono Celular</label>
            <input type="text" class="form-control" [(ngModel)]="telefono.telCelular" name="tcel">
          </div>

          <div class="col-md-3">
            <label for="email">E-mail</label>
            <input type="email" class="form-control" [(ngModel)]="telefono.email" name="email">
          </div>         
          </div>
        </div>
      </div>


      <button type="button" (click)="agregar()" class="btn btn-primary">Add</button>

按钮agregar向tfonos添加了一个元素,因此div被复制了,问题是[[ngModel)]也被复制并将它们绑定在一起,对我而言,理想的情况是为每个复制提供不同的ngModel实例或类似的东西。

1 个答案:

答案 0 :(得分:0)

您应该将Telefono实例放入tfonos数组中。

<div class="telefono">
  <label>Telefonos</label>
  <div class="tel" *ngFor="let t of tfonos; let i = index">
    <div class="row">
      <div class="col-md-2">
        <label for="tfijo">Telefono fijo</label>
        <input type="text" class="form-control" [(ngModel)]="t.telFijo" 
[name]="'tfijo' + i">
     </div>
      <div class="col-md-2">
        <label for="tcel">Telefono Celular</label>
        <input type="text" class="form-control" [(ngModel)]="t.telCelular" 
[name]="'tcel' + i">
      </div>

      <div class="col-md-3">
        <label for="email">E-mail</label>
        <input type="email" class="form-control" [(ngModel)]="t.email" 
[name]="'email' + i">
      </div>         
    </div>
  </div>
</div>