首页 > 解决方案 > 通过赋值和使用 patchValue() 为 formGroup 对象设置值有什么区别?

问题描述

如果我使用 Reactive Form 的 patchValue() 函数为我的对象赋值,如果我通过赋值运算符为它赋值会有什么不同?

我已经运行了代码并将值设置为“客户”对象,即:两者的工作方式相似。有人可以告诉我是否有任何我遗漏的细微潜在差异,或者是否有任何我没有得到的明显差异?


客户类:customer.ts

export class Customer {
    id: number;
    name: string;
    age: number;
    active: boolean;
    myproduct: {
        p_id : number;
    }
}

客户对象:create-customer-component.ts

customer = this.fb.group({
    id: null,
    name : ['', [Validators.required, Validators.minLength(4)]],
    age : ['', [Validators.required, Validators.min(18),Validators.max(100)]], 
    active: false,
    myproduct:this.fb.group(
      { p_id : null
      })
  })

上述两个选项

this.customer.value.myproduct.p_id = 1;
this.customer.patchValue({p_id : 2}) ;

标签: angular8reactive-forms

解决方案


您可以设置值,但它不会显示在输入框中,或者您可以使用 this.customer.controls['p_id '].setValue('Any Id');


推荐阅读