我正在尝试创建一个连接到ngModel的动态表单,以便用户根据需要添加更多控件。 正如图片所示:
图片
除了添加一组新的控件时,窗体的行为与预期相同,因为它会擦除之前输入的内容。 即使模型没有改变。 我创建了这个plunkr来演示我正在谈论的行为。
这是我写的html模板:
<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>和打字稿组件定义:
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'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:
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 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!
最满意答案
您的控件需要独特的名称才能在Angular2中正常工作。 所以做到以下几点:
<td> <input required type="number" class="form-control" [(ngModel)]="work.cost" name="cost-{{i}}"> </td>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>
更多推荐
发布评论