After a long break, let’s get back into the flow with a simple tuts.
No server-rendering-worker-asynchronous-resolution-injection here, just something that everybody use: forms!
Today we take a look at how template-driven forms work in Angular 2.
A 5-minutes read to slowly get back in form.
First we need to import FormsModule into our app.module.ts file:
Then we create the HTML template:
First we create a variable that will reference ngForm and contain the form itself.
On submit, we will trigger the function onFormSubmitted and pass this variable.
Then we create some inputs for the user.
([ngModel]) will activate the double binding and store everything into the user object.
The ngModelGroup directive will create an object address inside this user object.
For the finishing the touch, we disable the submit button if the form is invalid.
Before jumping into the Controller, let’s create an Interface that will formalize the data structure:
The only thing left now is the Controller!
We grab our User Interface and initialize our user.
Finally, the onFormSubmitted function where you do your business logic.
We log the userForm.value and our user variable.
At this point, both have the same content and that’s what we expected!
From here the power is yours, use the form or the model.
What will be the consequences if we change the value of the form in the onFormSubmitted function?
What about changing the value of the user model?
What about using [ngModel] or ngModel instead of ([ngModel])?
I’ll let you think about this ;).