AppDividend
Latest Code Tutorials

Angular 9/8/7 Forms Example | Angular Template-driven Example

1

Web applications are generally doing one of two things, either displaying data or collecting the data from the user. The way we collect data through web applications via the use of forms and more specific form elements.

When we create the forms in web apps, we build them to do the standard set of things for a way to save the data, for a way to know when the user changes data, for validating the data, and for showing errors to end-users.

Since web forms are a standard part of web app development, Angular has dedicated coding in its module to help when working with forms.

If you are new to Angular 8, then check out my Angular 9 Tutorial. If you do not know how to upgrade to Angular 8 via Angular CLI, then check out my Angular 9 Upgrade tutorial. Managing user input with forms is the cornerstone of many web applications.

The web app uses forms to enable the users to log in, to update a profile, to enter sensitive information, and to perform many data-entry tasks.

Angular 9 Forms

Angular forms provide data binding both in and out. Angular forms also provide indicators out of the box for you to know when the form fields have modified from their original value and when they are valid or invalid.

It also provides inbuilt data validators and the ability to create your own. 

Even async validators that can run the validation as the user changes input value. It also wraps up the form fields into the object structure for ease of use on submission. 

There are two main approaches to crafting forms in Angular. 

  1. Template-driven: It is a kind of form where the majority of the form logic is crafted in the HTML template mark-up.
  2. Model-driven: It is a kind of form where the majority of the form logic is crafted in the angular component class.

Overall, the form support built into Angular covers the wide range of the input collection scenarios.

Angular 9 Template-driven forms

To make use of the forms module in your angular 9 application, you need to add it to the list of imports for your Angular module. 

In the app.module.ts file, we can add the new import statement and bring in the forms module from the Angular forms package. 

Then we can insert the forms module to the imports property array.

See the following code inside the app.module.ts file.

// app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';

import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

The forms module contains all the forms directives and constructs for working with forms. With that in place, we are ready to start creating the form in Angular 9.

Now, write the HTML code inside the app.component.html file.

<form #corona = "ngForm" (ngSubmit) = "onClickSubmit(corona.value)" >
  <input type = "text" name = "patient_name" placeholder = "name" ngModel>
  <br/>
  <input type = "text" name = "patient_age" placeholder = "age" ngModel>
  <br/>
  <input type = "submit" value = "submit">
</form>

In Angular, the template-driven approach to creating forms makes use of the templates syntax to build form interactions all within your HTML template mark up. 

With the forms module included, Angular is going to be on the lookout for any form elements in your templates. 

It does this through the inbuilt ngForm directive which has form as part of its selector value.

So, you don’t need to tell Angular you have a form when you use the template-driven approach. But, you do need to tell it what fields are going to be part of the form. This is done through the ngModel directive.

The ngModel directive is designed to work with the name attribute that is native to html elements.

Since the form field already has a name attribute with the value of patient_name and patient_age, the form control that the ngModel directive will create will get the name patient_name and patient_age, even though the mark up consists of multiple form field elements.

Angular’s form system only knows about the patient_name and  patient_age right now because those are the ones with the ngModel directive on it.

Angular has a directive named ngSubmit() that is designed to be used on a native form element to intercept the default html form submit action and do what you want. 

So, on the form element, we add an event binding using the parentheses around ngSubmit() and set it equal to a function call that we will create of onSubmit.

Since there is a button in the form of type Submit, the click action of that will trigger form submission. That part is native html behavior for a form. 

Okay, we are going to need to create that onClickSubmit() function on the component class, but we also need to pass it the form information since we are building everything in the template. This can be done by using the hash on the form element to capture a handle to the form that Angular creates. 

So, on the form element, we put #corona, remembering that these template reference variables can have whatever name we want, and we set that equal to ngForm in double-quotes.

Angular will export a form group object into the media item form variable for us. The form group is the underlying model Angular uses for the form. 

From here we can pass the value of the form to the onSubmit method by using the corona.value, and then over in the app.component.ts file, we can add the onClickSubmit() method naming the parameter media item and console log it for now.

See the following code inside the app.component.html file.

# app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
  onClickSubmit(formData) {
    console.log('Coronal Effected Patient name is : ' + formData.patient_name);
    console.log('Coronal Effected Patient age is : ' + formData.patient_age);
 }
}

Save the file and start the dev server.

ng serve -o

Now, you will be able to log the patient_name and patient_age.

In the general scenario, we want to pass that object to the POST request to the backend server to store the user’s data.

Conclusion

Template-driven forms in Angular 9 are useful for adding the simple form to an app, such as the email list signup form.

They’re easy to add to any app, but they don’t scale as well as reactive forms.

If you have very basic requirements and logic that can be managed solely in the template, then and then use the template-driven forms.

1 Comment
  1. Amit Parmar says

    Thanks for the guide

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.