gpt4 book ai didi

angular - 如何在 Angular 7 中为 formControl 设置动态值

转载 作者:太空狗 更新时间:2023-10-29 18:07:32 26 4
gpt4 key购买 nike

我有一个拖放式 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,所以我该怎么做。

谢谢!

最佳答案

您可以使用 SetValue FormControl 的方法:

setValue():

Sets a new value for the form control.

在你的情况下它会是这样的:

this.userForm.controls['TemplateJson'].setValue(this.data.TemplateJson);

Stackblitz_Demo

关于angular - 如何在 Angular 7 中为 formControl 设置动态值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55645014/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com