Angular Forms:
Forms in Angular 4 can be designed on two approaches.
As you can see below , we have a Template based design and the other being a Reactive based design.
Here we will try to understand the Template based design:
In the template driven approach all the functionalities are added to the Form(HTML).
To get started with the template driven approach, we need to import the FormsModule from '@angular/forms' and import them into our application module file.
Now let us consider the below HTML code:
- As soon as Angular sees the form tag it understands that it has to create the Javascript object representing our form. So to make it understand that this is indeed an Angular form we have marked the Local reference (f) as ngForm. ngForm is a directive provided by Angular and has numerous functions related to forms.
- We have two input fields "username" and "email". To make the Angular form know that these fields are required in the javascript form object , we have to add ngModel. ngModel marks these parameters for the Angular form.
- The Javascript Form object maintains a key value pair of the form controls. So we need to provide the key (the value is marked by the ngModel) which is the name attribute in the form elements. E.g. Checkout the name attribute in our input tags.
- We can also see that we don't have an action attribute mentioned in our form. This is because, we do not want to hit any service before validating our form.
- Submit button click does not have any function call on it. However we can see that there is a (ngSubmit) directive, that takes advantage of the default Javascript behaviour and has a callback function to handle our event.
With the above changes made into our HTML we are ready to access the Javascript Form object in our typescript file.
The Typescript file:
- We can access the Form element by passing the local reference( in our case f )
- To access the Javascript Form object we need to use ngForm
- One other alternative is to use the ViewChild property that also gives us the same Javascript form object.
A typical Javascript form object is shown below:
For more details into the other aspects of Form handling such as Validators, setting default values, using the form object, Reactive Forms and many more, register for my Angular 4 course.
Thanks and Happy Reading!