我有拖放formBuilder,我们可以使用拖放创建表单,所以现在我面临的问题是我在html中隐藏了TempleteJson字段。
这是html代码
<form [formGroup]="userForm" (ngSubmit)="onSubmit()">
<div class="form-group">
<label>Form Name:</label>
<input type="text" class="form-group" formControlName="TemplateName" />
</div>
<div class="form-group">
<input type="hidden" class="form-group" formControlName="TemplateJson" />
</div>
<div class="form-group">
<label>CreatedOn:</label>
<input type="date" class="form-group" formControlName="CreatedOn" />
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
这是component.ts文件
formBuilder: any;
formData: any;
data: any;
ngOnInit() {
var id = this.route.snapshot.paramMap.get('id');
this.dataService.GetFormById(+id).subscribe(response => {
this.data = response['TemplateJson'];
this.generateForm();
},
err => {
this.generateForm();
});
initJq();
}
userForm = new FormGroup({
TemplateName: new FormControl(),
TemplateJson: new FormControl(),
CreatedOn: new FormControl(),
});
onSubmit() {
console.log(this.userForm.value);
this.dataService.addFormTemplate(this.userForm.value);
}
现在在this.data中,我有一个json,我想在TemplateJson FormControl中设置该json,那么我该怎么做。
谢谢!
答案 0 :(得分:3)
setValue():
设置表单控件的新值。
因此您可以像这样使用它:
this.userForm.controls['TemplateJson'].setValue(this.data.TemplateJson);
答案 1 :(得分:2)
我遇到了类似的问题,我在订阅后尝试将'setValues'与'this.class.attribute'一起使用,并且出现“无法读取未定义的值”错误。原来,您必须在订阅中使用setValue。
//My Get method
getX(): void {
const id = +this._route
.snapshot.paramMap.get('id');
this._xService.getX(id)
//Now my subscribe
.subscribe(x => {
this.x = x;
//And my setValue inside my subscribe
this.nameOfYourForm.setValue({
formAttribute1: this.x.Attribute1,
//The customer attribute should match the name in the API / database and not the name in your class
})
})
}
希望这对某人有所帮助。
答案 2 :(得分:0)
设置或更新反应性表单可以使用patchValue和setValue来完成表单控制值。但是,在某些情况下最好使用patchValue。
patchValue不需要在参数内指定所有控件,即可更新/设置表单控件的值。另一方面,setValue要求填写所有“表单控件”值,如果未在参数中指定任何控件,则它将返回错误。
在这种情况下,我们将使用patchValue更新userForm
中的值。
如果TemplateJson中的属性与FormControlNames相同,则可以通过以下方式简单地做到这一点:
this.userForm.patchValue(this.data)
如果名称不同,
this.userForm.patchValue({
property1: this.data.bbb
property2: this.data.aaa
.
.
})