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

16

我有一个拖放的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数据,我想将这个JSON设置到TemplateJson表单控件中,应该怎么做呢。

谢谢!


你的 generateForm() 函数在哪里? - Robert
1
这是关于响应式表单的一些基础知识。你可以轻松地在 https://angular.io/guide/reactive-forms 上找到答案。 - Sachin Gupta
@Robert的问题不在generateForm()函数中,而我没有在这里提到这个函数,因为我认为这个函数对问题没有意义。 - Ronak Dumaniya
this.userForm.get('TemplateJson').setValue(this.data.TemplateJson) - raw_hitt
3个回答

31

您可以使用FormControl的setValue方法:

setValue():

为表单控件设置一个新值。

在您的情况下,它将是这样的:

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

Stackblitz演示


9

我在这里回答了一个类似的问题,并且提供了更好的解释和示例。

使用patchValuesetValue都可以设置或更新响应式表单控件的值。然而,在某些情况下,使用patchValue可能更好。

patchValue不需要在参数中指定所有控件,就能够更新/设置表单控件的值。另一方面,setValue需要填写所有表单控件的值,并且如果任何控件没有在参数中指定,它会返回一个错误。

在这种情况下,我们将使用patchValue来更新userForm中的值。

如果TemplateJson中的属性与FormControlNames相同,可以简单地按照以下方式进行操作:

this.userForm.patchValue(this.data) 

如果名称不同,
this.userForm.patchValue({
  property1: this.data.bbb
  property2: this.data.aaa
  .
  .
}) 

在this.data中,我只有一个JSON,我想将其设置为TempleteJson,其他值来自表单。 - Ronak Dumaniya
好的,请稍等。您希望何时分配这些值? - wentjun
是的,而且这个数据可能是异步的,请注意检查。 - Ronak Dumaniya
但是表单不是在订阅中生成的吗? - wentjun

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 x attribute should match the name in the API / database and not the name in your class
       })
    })
  }

希望这能帮到某些人。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接