Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 813
ilyablbnv Avatar asked Nov 28 '25 05:11

ilyablbnv


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

like image 198
Pankaj Parkar Avatar answered Nov 30 '25 18:11

Pankaj Parkar