通过赋值和使用patchValue()为formGroup对象设置值之间有什么区别?

时间:2019-10-08 10:48:11

标签: angular8 reactive-forms

如果我使用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}) ;

1 个答案:

答案 0 :(得分:0)

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