0

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

Gynteniuxas
  • 7,035
  • 18
  • 38
  • 54
RANA 04
  • 48
  • 7
  • I assume `data` means that json in the first block? If it's literal json, then first you'll need to convert it to object (`JSON.parse(data)`) – Gynteniuxas Oct 16 '20 at 10:51
  • { "name": "", "address": { "line1": "", "pincode_id": "" } } is the actual format that i have to pass ..... how to pass the data inside of data – RANA 04 Oct 16 '20 at 17:01

1 Answers1

0

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

machal
  • 34
  • 1
  • but my code flow should be as a { "name": "", "address": { "line1": "", "pincode_id": "" } }...... is that possile in that way (i.e json inside of json ) – RANA 04 Oct 16 '20 at 16:59
  • 1
    That is the role of mapping. You can ensure you have the correct form after submition – machal Oct 18 '20 at 12:20