简体   繁体   中英

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 :)

I have created simply Plunker example 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). 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. But the problem is we're having same name attribute for all element which is 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.

<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

Note: Somehow [attr.name]="'name'+i" isn't working.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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