Angular Tutorial: Template-Driven vs Reactive Forms šŸš€

beginner
24 min

Angular Tutorial: Template-Driven vs Reactive Forms šŸš€

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! šŸŽÆ

What are Angular Forms? šŸ“

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 šŸ’”

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.

Creating a Template-Driven Form šŸ“

To create a Template-Driven Form, you'll first need a form group and form control.

typescript
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 šŸ’”

Validation in Template-Driven Forms is also done using Angular's built-in directives such as required, email, and custom validators.

typescript
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 šŸ’”

Reactive Forms use TypeScript classes to create and manipulate forms. They are ideal for complex forms and offer more flexibility in handling forms programmatically.

Creating a Reactive Form šŸ“

To create a Reactive Form, you'll first need a FormGroup and FormControls.

typescript
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 šŸ’”

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.

typescript
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.

Which to Choose? šŸ’”

The choice between Template-Driven and Reactive Forms depends on the complexity of your form and your preferences.

  • If you're working with a simple form and prefer a more template-driven approach, go with Template-Driven Forms.
  • If you're working with a complex form or need more control over form programmatically, go with Reactive Forms.

Quiz šŸ’”

Quick Quiz
Question 1 of 1

Which approach is ideal for complex forms with more control over forms programmatically?

Conclusion āœ…

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.