ilyablbnv ilyablbnv - 1 year ago 62
HTML Question

Why angular2 form works incorrectly with html <form> element?

I've noticed some strange behavior of

element in ng2 and I need someone to explain me it :)

I have created simply Plunker example

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
element like this
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.

Answer Source

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)]="" name="{{'name'+i}}">
      <select [(ngModel)]="param.type" name="{{'type'+i}}">
          <option *ngFor="let type of types" [ngValue]="type">{{type}}</option>

Demo Plunkr

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download