带有ngFor元素的ngModel的动态angular2形式 [英] Dynamic angular2 form with ngModel of ngFor elements

查看:129
本文介绍了带有ngFor元素的ngModel的动态angular2形式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建连接到ngModel的动态表单,该表单允许用户根据需要添加更多控件.就像下面的图片一样:

I'm trying to create a dynamic form connected to a ngModel which allows user to add more controls as needed. Just as the picture bellow:

除添加新的控件集外,该窗体的行为与预期的一样,因为它会删除先前输入的内容.即使模型没有更改.我创建了这个 plunkr 来演示我在说的行为.

The form behaves as expected except when adding a new set of controls as it erases the previous input's content. Even though the model is not changed. I created this plunkr in order to demonstrate the behavior I am talking about.

这是我写的html模板:

This is the html template I wrote:

<tr *ngFor="let work of works; let i = index">
  <td>
    <select required id="cliente" class="form-control" [(ngModel)]="work.operation" name="operation">
      <option>Operation 1</option>
      <option >Operation 2</option>
    </select>
  </td>

  <td>
    <input required type="number" class="form-control" [(ngModel)]="work.cost"
           name="cost">
  </td>

  <td>
    <input required id="horas_maquina_previstas" type="number" class="form-control" [(ngModel)]="work.hours"
           name="hours">
  </td>

  <td>
    <button type="button" class="btn btn-danger btn-circle" (click)="removeWork(i)">Remove</button>
  </td>
</tr>

和打字稿组件定义:

import {Component, ChangeDetectionStrategy} from '@angular/core'

@Component({
  selector: 'my-app',
  templateUrl: 'src/app.html'
})
export class App {
    works = [];

    addWork(){
        this.works.push({});
    }

    removeWork(index){
        this.works.splice(index, 1);
    }

    get diagnostic() {
        return JSON.stringify(this.works);
    }
}

我无法理解这种行为,我发现的所有相关问题都是关于较旧版本的angular的,而没有一个类似的问题.

I can't understand this behavior, and all the related questions I found were about older versions of angular and none had a similar problem.

推荐答案

您的控件需要唯一的名称才能在Angular2中正常工作.因此,请执行以下操作:

Your controls need unique names to work properly in Angular2. So do the following:

<td>
    <input required type="number" class="form-control" [(ngModel)]="work.cost"
            name="cost-{{i}}">
</td>

这篇关于带有ngFor元素的ngModel的动态angular2形式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆