Welcome back to CodeYourCraft! Today, we're diving deep into one of the most crucial concepts in Angular: Template-Driven vs Reactive Forms. By the end of this lesson, you'll be able to choose the right form for your project and understand why Angular offers two different approaches. Let's get started! šÆ
In Angular, forms are used to capture and validate user input. They come in two flavors: Template-Driven Forms and Reactive Forms. Both forms share similar functionalities but have different approaches to creating and managing forms.
Template-Driven Forms rely on the Angular Template syntax to create and manipulate forms. They are easy to set up and ideal for small and simple forms.
To create a Template-Driven Form, you'll first need a form group and form control.
import { Component } from '@angular/core';
@Component({
selector: 'app-template-form',
template: `
<form #myForm="ngForm">
<label>Name:</label>
<input [ngModel]="model.name" name="name" required>
<br>
<label>Email:</label>
<input [ngModel]="model.email" name="email" required email>
<br>
<button (click)="onSubmit(myForm)">Submit</button>
</form>
`,
})
export class TemplateFormComponent {
model = { name: '', email: '' };
onSubmit(form: NgForm) {
console.log(form.value);
}
}š Note: In the above code, we have created a form using the ngForm directive, and we have used the [ngModel] directive for two-way data binding between form controls and components.
Validation in Template-Driven Forms is also done using Angular's built-in directives such as required, email, and custom validators.
import { Directive, ElementRef, Input, Validators, Validator, FormControl } from '@angular/forms';
@Directive({ selector: '[myValidity]' })
export class MyValidityDirective implements Validator {
constructor(private el: ElementRef) {}
validate(control: FormControl) {
const value = control.value;
const minLength = value.length > 3;
const maxLength = value.length < 20;
const valid = minLength && maxLength;
control.setValue(value.toUpperCase());
return valid ? null : { myValidity: { valid } };
}
}š Note: In the above code, we have created a custom validator that checks the length of the input.
Reactive Forms use TypeScript classes to create and manipulate forms. They are ideal for complex forms and offer more flexibility in handling forms programmatically.
To create a Reactive Form, you'll first need a FormGroup and FormControls.
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
@Component({
selector: 'app-reactive-form',
template: `
<form [formGroup]="myForm">
<label>Name:</label>
<input formControlName="name">
<br>
<label>Email:</label>
<input formControlName="email">
<br>
<button (click)="onSubmit()">Submit</button>
</form>
`,
})
export class ReactiveFormComponent {
myForm: FormGroup;
constructor(private fb: FormBuilder) {
this.myForm = this.fb.group({
name: ['', Validators.required],
email: ['', [Validators.required, Validators.email]]
});
}
onSubmit() {
console.log(this.myForm.value);
}
}š Note: In the above code, we have used the formControlName directive to bind the form controls to the Reactive Form.
Validation in Reactive Forms can be done using the same built-in validators as in Template-Driven Forms, and also by adding validators to the form controls directly.
import { FormBuilder, Validators, FormGroup } from '@angular/forms';
const myValidity = (control: FormControl) => {
const value = control.value;
const minLength = value.length > 3;
const maxLength = value.length < 20;
const valid = minLength && maxLength;
return valid ? null : { myValidity: { valid } };
};
@Component({
selector: 'app-reactive-form',
template: `
<form [formGroup]="myForm">
<!-- form controls -->
</form>
`,
})
export class ReactiveFormComponent {
myForm: FormGroup;
constructor(private fb: FormBuilder) {
this.myForm = this.fb.group({
name: ['', [Validators.required, myValidity]],
email: ['', [Validators.required, Validators.email]]
});
}
}š Note: In the above code, we have added our custom validator myValidity to the form control.
The choice between Template-Driven and Reactive Forms depends on the complexity of your form and your preferences.
Which approach is ideal for complex forms with more control over forms programmatically?
By now, you should have a solid understanding of both Template-Driven and Reactive Forms in Angular. Mastering these forms will help you create interactive and validated user interfaces with ease. Happy coding! š
That's all for today's lesson. I hope you found it informative and engaging. Stay tuned for more in-depth tutorials on Angular and other web development topics right here at CodeYourCraft! š¤
š” Pro Tip: Practice by building a form in each approach to get a feel for their differences and advantages.