Search code examples
angularangular-materialangular8angular-formsangular-json

ANGULAR 8 - how to pass the data in which the json inside of json


In angular 8 my json format to pass the data is like

 {
  "name": "",
  "address": {
    "line1": "",
    "pincode_id": ""
  }
}

I create the format to pass the data to submit the form

Format() {
    let data = this.Form.controls;
    let ctofclass = new type();
    ctofclass.name = data['name'].value;
    ctofclass.line1 = data.address['line1'].value;
    ctrofclass.pincode_id = data.address['pincode_id'].value.id;
    return ctofclass;
  }

class type {
  name: string;
  line1: string;
  pincode_id:any;
  
}

how to pass the data in which the json inside of json
when i use this format I got an error in this line below:

ctrofclass.line1 = data.address['line1'].value;

core.js:6260 ERROR TypeError: Cannot read property 'value' of undefined

the address is inside of json and how to pass the data to submit the form


Solution

  • You need to either set address as formGroup and line1 and pinecode_id as formControls or use just pinecode_id and line1 as separated formcontrols without grouping them inside address if address has no special value on itself.

    Example using second solution (simplest):

    CustomFormControl = formbuilder.group({
       name: [initialValue],
       pincode_id: [address.pincode_id] // mapping is done here
       line1: [address.line1]
    })
    

    Then You can access form values like this CustomFormControl.controls[name].value