Wal*_*ter 6 angular-template angular angular-forms
我正在使用最近发布的 Angular 2.0.0,基本上我有一个组件来初始化它的表单模板的值,该模板由一个输入文本框和一个带有两个输入文本框的 FormGroup 的 formArray 组成。
初始化完成后,绑定工作正常,但是当我将新的 FormGroup 推送到 formArray 时,表单值不会反映新添加的项目,直到我在最初绑定的某个文本框中进行了一些值更改。为什么会出现这种行为,以及如何在添加某些动态 FormGroup 时更新表单值?
我的组件和模板代码是这样的:
//initialize the form values
//this_fb is the form builder
setControlsValues(){
this.form_band = this._fb.group({
name : [ 'test', [ Validators.required ] ],
bands : this._fb.array([
this._fb.group({
name : [ 'band 1', [ Validators.required] ],
score : 10
}),
this._fb.group({
name : [ 'band 2', [ Validators.required] ],
score : 8
})
])
});
}
//push a new FormGroup when user click button
addBand(){
this.form_band.controls.bands.controls.push(
this._fb.group({
name : [ '', Validators.required ],
score : 0
})
);
}Run Code Online (Sandbox Code Playgroud)
<form [formGroup]="form_band" validate="off">
<div class="form-group">
<label for="name">Name:</label>
<input type="text" class="form-control" formControlName="name" autocomplete="off">
</div>
<div class="form-group" >
<h4>Bands</h4>
<div formArrayName="bands">
<div *ngFor="let band of form_band.controls.bands.controls; let i=index">
<div [formGroupName]="i">
<input type="text" class="form-control" formControlName="name">
<input type="text" class="form-control" formControlName="score">
</div>
</div>
</div>
<button type="button" class="btn" (click)="addBand()">Add band</button>
</div>Run Code Online (Sandbox Code Playgroud)
解决了
我试图将新表单组推送到表单数组的控件属性,并且必须将其推送到表单数组本身。
我将 addBand 方法更改为:
addBand(){
this.form_band.controls.bands.push(
this._fb.group({
name : [ '', Validators.required ],
score : 0
})
);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4325 次 |
| 最近记录: |