Angular Template-Driven Forms
Syntax
<form #form="ngForm" (ngSubmit)="onSubmit()">
<label>
Name:
<input type="text" name="name" ngModel required>
</label>
<label>
Email:
<input type="email" name="email" ngModel required email>
</label>
<button type="submit" [disabled]="form.invalid">Submit</button>
</form>
Example
import { Component } from '@angular/core';
@Component({
selector: 'app-contact-form',
templateUrl: './contact-form.component.html',
styleUrls: ['./contact-form.component.css']
})
export class ContactFormComponent {
onSubmit() {
console.log('Form submitted!');
}
}
Output
The above example generates an HTML form with two input fields for name and email, and a submit button. When the form is submitted, the console will display the message "Form submitted!".
Explanation
Angular Template-Driven Forms is a technique for creating forms in Angular that relies on the ngModel
directive. The ngModel
directive binds a form control to a property on the component. By default, ngModel
uses two-way binding to keep the value in sync between the control and the component property.
The #form="ngForm"
creates a reference to the form and assigns it to the form
variable.
The (ngSubmit)="onSubmit()"
handles the form submission and triggers the onSubmit()
method when the form is submitted.
The name
and email
input fields use the ngModel
directive and have required
and email
validators.
The [disabled]="form.invalid"
is used to disable the submit button if the form is invalid.
Use
Template-Driven Forms are convenient for simple forms because they require less code and use the built-in validation directives. It's easy to get started and create a simple form. However, for complex forms, it's best to use Reactive Forms, which provide more control and flexibility.
Important Points
- Template-Driven Forms rely on
ngModel
directive and two-way binding. - The template is the single source of truth for the form structure and validation rules.
- The
ngForm
directive is used to create a reference to theform
variable. - The
ngSubmit
event is used to trigger theonSubmit()
method when the form is submitted. - The
ngModel
directive binds the form control and the component property.
Summary
Template-Driven Forms are a simple and convenient way to create forms in Angular. They use two-way binding to keep the form control and the component property in sync. We bind the form reference to an HTML form using (ngSubmit)="onSubmit()"
to handle the form submission. However, for more complex forms, it is recommended to use Reactive Forms, which provide more control and flexibility.