Angular 2 Template-Driven Forms in One Go

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.

Angular 2 form

The almighty NgForm

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:

Module: Ready.
Template: Ready.
Interface: Ready.

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.

Quiz time!

3 questions…

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 ;).

2 Comments

  1. David David
    February 22, 2017    

    Thanks for this awesome article!
    What will be the consequences if we change the value of the form in the onFormSubmitted function?
    It will not change the user model?
    What about changing the value of the user model?
    It will also change the userForm value because it’s double bound.
    What about using [ngModel] or ngModel instead of ([ngModel])?
    [ngModel] wouldbe one-way binding, though I am not sure about the ngModel.
    What do you think?

    Cheers,
    David

  2. Matthieu Drula Matthieu Drula
    February 26, 2017    

    Exactly David!
    I’ll add that modifying the model will update the UI too.
    Here is an example of using ngModel:
    {{name.value}
    It will create a variable that will not be directly attached to the component’s scope but to the form’s one.
    Those edge cases that are nice to know, [ngModel] is good enough.

Leave a Reply

1 Shares