简体   繁体   English

从 JSON 对象 angular 10 到嵌套表单组的设置值

[英]setvalues to nested formgroup from the JSON object angular 10

I do have JSON object coming from backend and would like to set values for it in better way.我确实有来自后端的 JSON 对象,并希望以更好的方式为其设置值。 What are the best approach I should consider?我应该考虑的最佳方法是什么?

I do know to manually set values to objects based on the key param.我知道根据键参数手动设置对象的值。

Is there any other optimized way I can do this?有没有其他优化的方法可以做到这一点?

 //backend response "response": { "senderCode": "123", "senderName": "test2", "receiverCode": "456", "name": "test", "contactnumber": "1233333333" } //formgroup structure this.Form = this.fb.group({ receiverCompanyCode: null, // Sender Information senderInformation: this.fb.group({ senderCompanyCode: [null], senderName: [null], }), // Contact Information contactInformation: this.fb.group({ name: [null, Validators.required], telephone: [null, Validators.required], }), });

may be this help you可能这对你有帮助

const response = {
      name: 'test',
      telephone: '1233333333'
};
this.contactInformation.setValue(response);

you have to manually map the data into form value您必须手动将数据映射到表单值

const mappedValue = {
receiverCompanyCode: response.receiverCompanyCode,
    senderInformation: {
        senderCompanyCode: response.senderCompanyCode,
        senderName: response.senderName,
    },
    contactInformation: {
        name: response.name,
        telephone: response.telephone,
    }
}
this.Form.patchValue(mappedValue);

or change the FormGroup structure and patch response value directly或者直接更改FormGroup结构和补丁响应值

this.Form = this.fb.group({
    senderCode: [null],
    senderName: [null],
    receiverCode: [null],
    name: [null],
    contactnumber: [null]
});
this.Form.patchValue(response);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM