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

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

问题描述

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

异常行为:如果我要添加 2 个或更多输入字段并删除非最后一个条目的输入,下次我添加新条目时,它会重置我刚刚删除的条目下方的所有条目.此外,不知何故新条目与上述条目绑定?

问题演示

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

这是我使用 ngFor 实现带有动态输入的模板驱动表单的方式.我指的是另一个 stackoverflow 帖子:angular-2-template-driven-form-with-ngfor-inputs

<div class="form-group"><label for="name">Name</label><input type="text" class="form-control" id="name"必需的[(ngModel)]="hero.name" name="name-{{i}}"#name="ngModel" ><div [hidden]="name.valid || name.pristine"class="警报警报-危险">姓名为必填项

感谢任何帮助.谢谢!

解决方案

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

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

所以我建议您使用 id 作为唯一名称:

让 uniqueId = 1;...添加新英雄(){var hero: Hero = new Hero(uniqueId++,'','');this.heroArray.push(英雄);}

在 html 中:

这是Plunker

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...

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?

demo of the issue

Here is my plunker: http://plnkr.co/edit/FjLg8VDDo3E6fHVgS8ah?p=preview

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!

解决方案

I like questions with the demonstration on the Plunkr:)

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.

So i offer you to use id as unique name:

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

and in html:

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

Here is the Plunker

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

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆