Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic angular2 form with ngModel of ngFor elements

Tags:

angular

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.

like image 616
Rafael Gil Avatar asked Jul 28 '16 14:07

Rafael Gil


1 Answers

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>
like image 191
Pace Avatar answered Oct 26 '22 11:10

Pace