简体   繁体   English

为什么angular2表单与html的工作不正确 <form> 元件?

[英]Why angular2 form works incorrectly with html <form> element?

I've noticed some strange behavior of <form> element in ng2 and I need someone to explain me it :) 我注意到ng2中的<form>元素有一些奇怪的行为,我需要有人来解释一下:)

I have created simply Plunker example https://plnkr.co/edit/vdrHJBNdd26y6YhPXTHD?p=preview 我创建了简单的Plunker示例https://plnkr.co/edit/vdrHJBNdd26y6YhPXTHD?p=preview

So now it is working fine. 所以现在它工作正常。 If you enter some value and click "Add parameter", input value will be updated in model and saved into input field. 如果输入一些值并单击“添加参数”,输入值将在模型中更新并保存到输入字段中。

But if you wrap your <div> with <form> element like this https://plnkr.co/edit/vdrHJBNdd26y6YhPXTHD?p=preview and input smth into a field and click again "Add parameter", form will be refreshed and your value will disappear (in model it still exists). 但是,如果你用<form>元素包装你的<div> ,如https://plnkr.co/edit/vdrHJBNdd26y6YhPXTHD?p=preview并输入smth到一个字段并再次点击“添加参数”,表格将被刷新,你的值将消失(在模型中它仍然存在)。 Can't figure out why it happens. 无法弄清楚它为什么会发生。 Thanks in advance for your answers. 提前感谢您的回答。

The reason is when form renders all its input with via help of ngFor , we display all the fields. 原因是当form通过ngFor帮助呈现all输入时,我们显示所有字段。 But the problem is we're having same name attribute for all element which is name="name" & name="test" . 但问题是我们对所有元素都有相同的名称属性,即name="name"name="test" So when new input gets added with name value '' & type this.types[0] ( String ) it applies the same value for all form element. 因此,当新的输入添加了name''type this.types[0]String )时,它为所有表单元素应用相同的值。

<form #form="ngForm">
    <div *ngFor="let param of paramsList; let i=index">
      <input type="text" [(ngModel)]="param.name" name="{{'name'+i}}">
      <select [(ngModel)]="param.type" name="{{'type'+i}}">
          <option *ngFor="let type of types" [ngValue]="type">{{type}}</option>
      </select>
    </div>
</form>

Demo Plunkr 演示Plunkr

Note: Somehow [attr.name]="'name'+i" isn't working. 注意:不知何故[attr.name]="'name'+i"无效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM