December 3, 2018

Nested Forms in Angular

This Article is based on Kara Ericksons talk about “Angular Forms” at the Angular Connect 2017.

https://www.youtube.com/watch?v=CD_t3m2WMM8&amp=&index=15

I am going to give you a quick example to get started with nested Forms.

TL;DR

  • Extract the HTML in new Component
  • Inject ControlContainer in new Component
  • Access the Form via ControlContainer.control
  • pass the parent Form into the nested Component with the [formGroup] directive
  • StackBlitz Example

Basic Form

We have a classic form to enter the name and the address of a person. Now we want to reuse the address block in other forms.

Nested Forms

Extracting the Form in a new Component is quite basic. We move the needed HTML into a new Component and wrap it in an <ng-container [formGroup]=”controlContainer.control”>.

In the Component class we need inject the ControlContainer, this will give us the access to the given FormGroup from the parent.

In the parent component, we need to replace the old HTML with the new component tag.

Don’t forget to add the [formGroup] Attribute and pass in a valid FormGroup.

If you try the StackBlitz example, you can see that after you press “save” the form with the nested Form results will be printed to the screen.

Troubleshooting

Error:
ERROR Error: formControlName must be used with a parent formGroup directive. You’ll want to add a formGroup
directive and pass it an existing FormGroup instance (you can create one in your class).
Solution:
Add a [formGroup] as attribute to your nested form component call.

Error:
ERROR TypeError: Cannot read property ‘get’ of undefined
Solution:
Inject the ControlContainer to the nested form component.

Related Posts

Avatar photo

theCodeCampus
Developer at thecodecampus </>

Our knowledge is not simply gained through reading - it is trained, tested and constantly being expanded. Because first and foremost, we are all developers at W11K. The know-how that we acquire here as developers, consultants and information architects flows immediately into our training courses and articles for theCodeCampus.


One response to “Nested Forms in Angular”

  1. Gregg B. Jensen says:

    Nice post, thank you for the example. It worked well for us.

Leave a Reply

Add code to your comment in Markdown syntax.
Like this:
`inline example`

```
code block
example
```

Your email address will not be published.