What are Template and Reactive forms in Angular?
In Angular, there are two ways to build forms: template-driven forms and reactive forms.
Template-driven forms are built using templates in the HTML markup. They are easy to use, but they do not provide as much control over the form as reactive forms.
To build a template-driven form, you can use the ngModel directive to bind the form controls to component properties. You can also use directives like ngSubmit and ngModelGroup to handle form submission and group form controls.
Here’s an example of a template-driven form in Angular:
<form (ngSubmit)="onSubmit()">
<label>
Name:
<input type="text" [(ngModel)]="name" name="name">
</label>
<button type="submit">Submit</button>
</form>In this example, the ngSubmit directive is used to handle form submission, and the ngModel directive is used to bind the value of the name input to the name property of the component.
Reactive forms, on the other hand, are built using a reactive programming approach. They provide more control over the form and allow you to create complex forms with advanced validation.
To build a reactive form, you can use the FormControl, FormGroup, and FormArray classes to create form controls, form groups, and form arrays, respectively. You can then use these classes to build the form and handle form submission.
Here’s an example of a reactive form in Angular:
import { Component } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms';
@Component({
selector: 'app-my-form',
templateUrl: './my-form.component.html'
})
export class MyFormComponent {
form: FormGroup;
constructor() {
this.form = new FormGroup({
name: new FormControl('')
});
}
onSubmit() {
console.log(this.form.value);
}
}<form [formGroup]="form" (ngSubmit)="onSubmit()">
<label>
Name:
<input type="text" formControlName="name">
</label>
<button type="submit">Submit</button>
</form>In this example, the FormGroup and FormControl classes are used to build the form and bind the name input to the name form control. The ngSubmit directive is used to handle form submission, and the formGroup directive is used to bind the form to the form property of the component.
Both template-driven forms and reactive forms have their own advantages and use cases. Template-driven forms are simpler and easier to use, but they are not as flexible as reactive forms. Reactive forms provide more control and are more suited to complex forms with advanced validation, but they require a deeper understanding of reactive programming.
