
Existing member? Log in and continue learning

See if you like it, start the course for free!

Unlock full course by purchasing a membership
The FormGroup Directive
The FormGroup Directive
Forms in Angular are one of those things that seem to work by some kind of magic. When working with Reactive Forms we would create Form Controls in some way, maybe through a Form Group:
loginForm = this.fb.nonNullable.group({ email: [''], password: [''], });
and then we somehow tie those controls to a standard <form>
DOM element:
<form> <input type="email" placeholder="email"/> <input type="password" placeholder="password" /> <button type="submit">Submit</button></form>
like this:
<form [formGroup]="loginForm" (ngSubmit)="onSubmit()"> <input formControlName="email" type="email" placeholder="email"/> <input fromControlName="password" type="password" placeholder="password" /> <button type="submit">Submit</button></form>
But what’s the deal with this formGroup
property, and the formControlName
properties? Why can we use an ngSubmit
event binding? These are not things
that exist on the standard <form>
DOM element, they come from Angular forms
specifically. But… how exactly does that work?
Understanding this can help us to understand Angular forms in more detail, and as well as that it can teach us a lot about how the more advanced features of Angular work more generally.
The Power of a Directive
The secret to powering these forms are directives. We have already covered
how directives provide us with a way to extend the behavior of existing
components/elements by matching against a selector
.
Let’s focus on just the <form>
itself. By giving it a formGroup
property, we
are going to trigger a match with the FormGroupDirective
. This is from the
Angular source code:
@Directive({ selector: '[formGroup]', providers: [formDirectiveProvider], host: {'(submit)': 'onSubmit($event)', '(reset)': 'onReset()'}, exportAs: 'ngForm'})export class FormGroupDirective extends ControlContainer implements Form, OnChanges, OnDestroy {
As you can see, it has a selector
of [formGroup]
. This is not something we
ever actually see — it is provided by Angular in the ReactiveFormsModule
. That
means that if we import the
Thanks for checking out the preview of this lesson!
You do not have the appropriate membership to view the full lesson. If you would like full access to this module you can view membership options (or log in if you are already have an appropriate membership).