1

I have these two following class:

export class Machine {
   name = '';
   computer = new Computer()
}

export class Computer {
   os = '';
}

then on my component using reactive form i have:

ngOnInit()  {  this.form = this.fb.group(new Machine())  }

and in my template:

 <input class="form-control" formControlName="name"> // the name works fine
 <input class="form-control" formControlName="computer.os">

and in console i get this error:

Cannot find control with name: 'computer.os'

Is it not possible to use FormBuilder.group like this?

1 Answer 1

1

In your case where you have the equivalent of a nested property (you have a form model with a 'computer' property with a nested 'os' property), you have to nest your form groups to achieve the same effect.

So, in your case, you'd need:

<div [formGroup]="form">
   <input formControlName="name" />
   <div formGroupName="computer">
      <input formControlName="os" />
   </div>
</div>

That structure above will give a form.value of:

 {
   name: <value of input field>
   computer: {
      os: <value of second input field>
   }
 } 

I used a div for my nested form group, but you can use any element (or even ng-container if you don't want to change your DOM structure)

To be honest, I've never seen examples where people use actual classes to represent their form models (i tend to see interfaces, usually) but since the formControlName directive is basically working with property names, it probably should still work.

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

2 Comments

and using the form.get('computer').value , how do i get the value?
you should be able to use your `form.get('computer.os').value

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.