I'm trying to create a dynamic form connected to a ngModel wich allows user to add more controls as needed. Just as the picture bellow:
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 behaviour 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 behaviour, and all the related questions I found were about older versions of angular and none had a similar problem.
Thank you!
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>
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.