Gag*_*ags 6 angular2-forms angular2-template angular
我正在使用Angular2 - Reactive Forms.一切正常,直到我想在Form中的一个字段中显示预先填充的值.
场景:页面上有多个按钮,每个按钮打开一个带有字段的表单
失败的场景:产品代码输入值变为空.
TS代码:
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
queryForm: FormGroup;
constructor(private _productService: ProductService, fb: FormBuilder) {
this.queryForm = fb.group({
'name': [null, Validators.compose([Validators.required, Validators.minLength(5)])],
'email': [
null, [Validators.required, Validators.email]
],
'message': [null,Validators.compose([Validators.required, Validators.minLength(5)])],
'pcode': [
null
],
})
}
Run Code Online (Sandbox Code Playgroud)
HTML表格:
<div *ngFor="let item of product">
<form action="#" [formGroup]="queryForm"
(ngSubmit)="submitForm(queryForm.value)" method="post"
novalidate="" class="text-left note" id="f_{{item.productId}}">
[ .... rest of the fields ...]
<div class="form-group hidden">
<input type="hidden " class="form-control " id="pcode " name="pcode"
formControlName="pcode" [value]="item.productCode" />
</div>
<div class="form-group">
<button type="submit" class="btn1" [disabled]="!queryForm.valid">Submit</button>
</div>
</form>
</div>
Run Code Online (Sandbox Code Playgroud)
我怎样才能实现这一目标?
更新:我们发现,你需要一个formArray而不是一个formControl.因此,在构建表单时声明:
this.queryForm = this.fb.group({
arrayOfData: this.fb.array([]) // name a proper name to array
})
Run Code Online (Sandbox Code Playgroud)
您可以使用setValue或patchValue在收到数据时,在其中迭代响应并将值修补到表单数组.patchValues在回调中调用-method(订阅).
patchValues() {
const control = <FormArray>this.queryForm.controls.arrayOfData;
this.items.forEach(x => {
control.push(this.patchValue(x.first_name, x.pcode))
})
}
patchValue(name, code) {
return this.fb.group({
name: [name],
pcode: [code]
})
}
Run Code Online (Sandbox Code Playgroud)
在你的模板中迭代formarray并记得设置formgroupname(这是索引):
<div formArrayName="arrayOfData">
<div *ngFor="let code of queryForm.controls.arrayOfData.controls; let i = index">
<div formGroupName="{{i}}">
<label>Name: </label>
<input formControlName="name" /><br>
<label>Product Code: </label>
<input formControlName="pcode" /><br>
</div>
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
原始答案:
您应始终在组件中设置表单值,而不是模板.您可以使用patchValue或setValue,当您收到服务中的值时...所以您可以这样做,例如在回调中(订阅):
this.myService.getSomeData()
.subscribe(data => {
this.item = data;
this.queryForm.patchValue({pcode: this.item.productCode})
});
Run Code Online (Sandbox Code Playgroud)
然后您不需要[value]="item.productCode"在表单中使用,而是使用表单控件来设置此值.
| 归档时间: |
|
| 查看次数: |
8451 次 |
| 最近记录: |