Rafael Gil
Rafael Gil

Reputation: 393

Dynamic angular2 form with ngModel of ngFor elements

I'm trying to create a dynamic form connected to a ngModel which allows user to add more controls as needed. Just as the picture bellow:

image

The form behaves as expected except when adding a new set of controls as it erases the previous input's content. Even though the model is not changed. I created this plunkr in order to demonstrate the behavior I am talking about.

This is the html template I wrote:

<tr *ngFor="let work of works; let i = index">
  <td>
    <select required id="cliente" class="form-control" [(ngModel)]="work.operation" name="operation">
      <option>Operation 1</option>
      <option >Operation 2</option>
    </select>
  </td>

  <td>
    <input required type="number" class="form-control" [(ngModel)]="work.cost"
           name="cost">
  </td>

  <td>
    <input required id="horas_maquina_previstas" type="number" class="form-control" [(ngModel)]="work.hours"
           name="hours">
  </td>

  <td>
    <button type="button" class="btn btn-danger btn-circle" (click)="removeWork(i)">Remove</button>
  </td>
</tr>

and the typescript component definition:

import {Component, ChangeDetectionStrategy} from '@angular/core'

@Component({
  selector: 'my-app',
  templateUrl: 'src/app.html'
})
export class App {
    works = [];

    addWork(){
        this.works.push({});
    }

    removeWork(index){
        this.works.splice(index, 1);
    }

    get diagnostic() {
        return JSON.stringify(this.works);
    }
}

I can't understand this behavior, and all the related questions I found were about older versions of angular and none had a similar problem.

Upvotes: 10

Views: 5392

Answers (1)

Pace
Pace

Reputation: 43817

Your controls need unique names to work properly in Angular2. So do the following:

<td>
    <input required type="number" class="form-control" [(ngModel)]="work.cost"
            name="cost-{{i}}">
</td>

Upvotes: 20

Related Questions