我正在尝试创建一个动态表单,与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>
和typescript组件定义:
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);
}
}
我无法理解这种行为,而且我找到的所有相关问题都是关于旧版本的angular,并且没有类似的问题。