0

I am trying to create nested object as below

myForm value: 
{
  "name": {
         "firstname":"abc",
         "lastname":"xyz"
   },
  "address": {
    "street": "assdasdasdsa",
    "postcode": "8000"
  }
}

In interface, there is option to specify string,number, array types syntax

I tried below options but no luck and it is throwing error "ERROR Error: Cannot find control with name:" (workarounds from SO and others didn't help)

export interface Customer {
    name: {
    firstname: string;
    lastname: string;
};
    addresses: Address[];
}

export interface Address {
    street: string;
    postcode: string;
}

Could you please provide me options to specify object as mentioned above?

Plunker- https://embed.plnkr.co/hQ6RtzCfPosfQl4HlbZQ/

In Angular 1, it was easy with scope object and using ng-model as "myForm.name.firstname"

Codepen tried in angular1 - https://codepen.io/nagasai/pen/mmYgbr and trying to replicate same in angular 2

6
  • Plunker is working fine? Commented May 29, 2017 at 10:39
  • yes ,Plunker url is working fine with name as string and I am trying to change it as object which is not working Commented May 29, 2017 at 10:42
  • well make a new interface for Name: export interface Name {firstname: string; lastname:string} address: export interface Address {street: string;postcode: string;} and customer: export interface Customer{name: Name;addresses:Address[]} Commented May 29, 2017 at 10:44
  • app.component.html:7 ERROR Error: Cannot find control with name: 'firstname' , getting same error after trying with above option Commented May 29, 2017 at 10:57
  • plnkr.co/edit/0DUzMNZ9VBwEJrASVuyR?p=preview Commented May 29, 2017 at 10:58

1 Answer 1

2

You have a form group name in your TS, which contains the form controls firstname and lastname. You had forgotten to apply that in your template. So you need to wrap the form controls with formGroupName:

<div formGroupName="name"> <!-- Here -->
  <div class="form-group">
    <label>Name</label>
    <input type="text" class="form-control" formControlName="firstname">
    <input type="text" class="form-control" formControlName="lastname">
 </div>

Forked Plunker

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks AJT, it works great.... :) not sure about downvote :) for this question :(
Glad to hear it worked out! Well you got an upvote from me ;P Have a nice day/evening/night and happy coding! :)
Thanks a lot AJT :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.