将模板驱动的表单与动态输入列表(ngFor)结合使用 [英] Using template driven form with dynamic input list (ngFor)

查看:73
本文介绍了将模板驱动的表单与动态输入列表(ngFor)结合使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Web开发的新手,并且正在使用angular2进行MEAN堆栈项目. 我正在尝试使用ngFor添加具有动态输入列表的模板驱动的表单-但是,我的实现方式确实观察到异常行为.我想知道我是否做对了...

I am new to web development and is working on a MEAN stack project using angular2. I am trying to add template-driven form with dynamic list of input using ngFor - however I did observe an abnormal behavior with the way I implement it. I am wondering if I am doing it the right way...

异常行为:如果我要添加2个或更多输入字段并删除非最后条目输入,则下次我添加新条目时,它将重置所有刚删除的条目以下的条目.另外,新的条目是否与上面的条目绑定在一起?

Abnormal behavior: If I were to add 2 or more input field and remove the non-last-entries input, the next time i add the new entries, it resets all the entries below the one I just deleted. In addition, somehow the new entries are binding with the entries above?

问题演示

这是我的朋克: http://plnkr.co/edit/FjLg8VDDo3E6fHVgS8ah?p=preview

这是我使用ngFor通过动态输入实现模板驱动形式的方式.我指的是另一个stackoverflow帖子:Angular-2-template-driven-form-with-ngfor-inputs

Here is the way that I implement template driven form with dynamic input using ngFor. I was referring to another stackoverflow post:angular-2-template-driven-form-with-ngfor-inputs

<div *ngFor="let hero of heroArray; let i = index">

             <div class="form-group">
            <label for="name">Name</label>
            <input type="text" class="form-control" id="name"
                   required
                   [(ngModel)]="hero.name" name="name-{{i}}"
                   #name="ngModel" >
            <div [hidden]="name.valid || name.pristine"
                 class="alert alert-danger">
              Name is required
            </div>
          </div>
      </div>

感谢您的帮助.谢谢!

Any help is appreciated. Thanks!

推荐答案

我喜欢在Plunkr上进行演示的问题:)

I like questions with the demonstration on the Plunkr:)

我认为问题与您的name属性有关.它应该是唯一的名称.将索引用作唯一值是错误的.更改阵列后将混合使用.

I suppose that the problem is related with your name property. It should be unique name. Using index as unique value is wrong. It will be mixed after changing your array.

因此,我建议您使用id作为唯一名称:

So i offer you to use id as unique name:

let uniqueId = 1;
...
addNewHero(){
  var hero: Hero  = new Hero(uniqueId++,'','');
  this.heroArray.push(hero);
}

和html中的

<input type="text" ... name="name-{{hero.id}}">

这是 柱塞

Here is the Plunker

这篇关于将模板驱动的表单与动态输入列表(ngFor)结合使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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