Javatpoint Logo
Javatpoint Logo

Template-driven Forms

Template-driven forms can be used for many applications i.e. log in, submit a request, place an order, data entry etc.

Now, let's create the form. Follow these steps:

Create a project

First, create a new project named angular-forms by using the following command:

Now, go to the project folder by using the following command.

Now, use the Angular CLI command ng generate class Hero to generate a new class named Hero:


Template-driven Forms

Go to your project folder angular-forms and open the hero.ts file under the app module. Write the following code:

The TypeScript compiler generates a public field for each public constructor parameter and when you create new heroes, it automatically assign the parameter's value to that field.

Here, alterEgo is optional and the constructor can omit it.

Create a Form component

An Angular form consists of two parts:

  • HTML based template
  • A component class to handle data and users

Now, generate a new component named HeroForm by using the following command:


Template-driven Forms

Write down the following code in hero-form.component.ts

Revise app.module.ts file

The app.module.ts file is used to define the application's root module. The template-driven forms reside in their own module. You need to add the FormsModule to the array of imports for the application module before using forms.

Use the following code inside app.module.ts file:

Here, we have imported FormsModule and added the FormsModule to the list of imports defined in the @NgModule decorator. This is used to access the application to all of the template-driven forms features, including ngModel.

Revise app.component.html file

The app.component.html is used to host the new HeroFormComponent. It is the application's root component. Write the following code in app.component.html

Create an initial HTML form template

Use the following code in hero-form.component.html

Style the form

Open style.css and use the following code to import the bootstrap file.

Add power list by using *ngFor

The hero form can choose power lists from a fixed list of agency-approved powers. Use the following HTML code immediately below the Alter Ego group in hero-form.component.html

The basic template-driven form is completed now. You can use the ng serve command to run the project.

Output:

Template-driven Forms

You can check here Hero's power.

Template-driven Forms
Next Topic#





Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA