23
The truth about Angular form
In this article i want to explain how to use angular forms directives in the right way, because i've observed that is not already clear how to use it correctly or what is the diferent about use template forms and built our owned form whith FormBuilder
class. I am not going to enter in how to create a form in angular only i want to explain the interesting things.
I'm going to start with something very simple but could be doubs about this.
The question is: What happens when we use <form #f="ngForm" ...
?
Someone could think that we're referencing our form, this could be true, but in reality more things are happening behind the scenes.
The truth about this is that when we import FormsModule
automatically NgForm
is avalilable in our view, this means that NgForm
is automatically attached to any <form>
in our view and is not necessary add explicitly ngForm
as an attribute.
Answering the question posed, when we use #f="ngForm"
in a form
tag in reality we're creating a FormGroup
! where f
is the type FormGroup
, this is so because this syntax says that we want to create a local variable for this view but, where did ngForm
cames from ? it came from the NgForm
directive.
At this moment you could think, ok f
variable is a FormGroup
, if you remenber a FormGroup
is composed by FormControls
and, where are they in our form ? Now comes into play NgModel
directive.
When we use ngModel
with no attribute vslue we are specifying that at first we want a one-way data binding, and this is important we want to create a FormControl
on this form with the name same as name attribute. NgModel
creates a new FormControl
that is automatically added to the parent FromGroup
.
Now we can build our form like this:
<!-- Creates a FormGroup-->
<form #f="ngForm" (ngSubmit)="onSubmit(f.value)">
<!-- Creates a FormControl with name email -->
<input name="email" type="email" ngModel >
<!-- Creates a FormControl with name password -->
<input name="password" type="password" ngModel >
</form>
In this simple way we can create a valid form in Angular using template forms, but create form with this way have some limitations, for example what happens if we want validate the password input, we cant specify validators for FormControls
and neither we can't listen the form events. If we aren't want do special stuff template form could be a great solution.
23