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

How to set dynamic value to formControl in angular 7

我有一个拖放功能 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 FormControl 中设置所以我该怎么做。

谢谢!

可以使用FormControl的SetValue方法:

setValue():

Sets a new value for the form control.

在你的情况下它会像:

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

Stackblitz_Demo

我已经回答了一个类似的问题,其中有更好的例子解释。

可以使用 patchValuesetValue 来设置或更新响应式表单表单控件值。但是,在某些情况下使用 patchValue 可能会更好。

patchValue 不需要在参数中指定所有控件,以便 update/set 表单控件的值。另一方面,setValue 要求填写所有表单控件值,如果您的任何控件未在参数中指定,它将 return 出错。

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

如果TemplateJson中的属性与FormControlNames相同,那么可以简单的这样做:

this.userForm.patchValue(this.data) 

如果名称不同,

this.userForm.patchValue({
  property1: this.data.bbb
  property2: this.data.aaa
  .
  .
}) 

我有一个类似的问题,我在订阅后尝试将 '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
       })
    })
  }

希望这对某人有所帮助。