Template-driven forms in Angular are an alternative way to handle forms, relying on directives in the template itself for form creation and validation. It's more suitable for simpler forms and is generally easier to get started with than reactive forms.
Here's a basic overview of using template-driven forms:
-
Import FormsModule:
// In your AppModule or another module where you intend to use forms import { FormsModule } from '@angular/forms'; @NgModule({ imports: [ FormsModule, // ...other modules ], // ...other configurations }) export class YourModule { }
-
Template Setup:
<!-- In your component's HTML template --> <form #myForm="ngForm" (ngSubmit)="onSubmit(myForm)"> <input type="text" name="firstName" ngModel required> <input type="text" name="lastName" ngModel required> <input type="email" name="email" ngModel required email> <!-- ...other form fields --> <button type="submit" [disabled]="!myForm.valid">Submit</button> </form>
-
Handling Form Submission:
// Inside your component class onSubmit(form: NgForm) { if (form.valid) { // Handle valid form submission const formData = form.value; //...do something with formData } else { // Handle invalid form // Display errors, mark fields as touched, etc. } }
Additional Functionality:
- NgModel: Used for two-way data binding to form controls.
- Template Reference Variables (#myForm): Reference form and its controls for validation and submission.
-
Form Validation: Use HTML attributes like
required, minlength, maxlength,
etc., along with Angular's built-in validation directives.
Template-driven forms are suitable for small to medium-sized forms where the logic and validation are defined directly in the template. However, for more complex scenarios or forms requiring dynamic behavior, reactive forms might be a better choice due to their explicit handling in the component class.