Template-driven FormsTemplate-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 projectFirst, 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: 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 componentAn Angular form consists of two parts:
Now, generate a new component named HeroForm by using the following command: Write down the following code in hero-form.component.ts Revise app.module.ts fileThe 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 fileThe 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 templateUse the following code in hero-form.component.html Style the formOpen style.css and use the following code to import the bootstrap file. Add power list by using *ngForThe 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: You can check here Hero's power. Next Topic# |