Angular Forms
Handling user input with forms is the cornerstone of many common applications.
Angular provides two different approaches to handling user input through forms: reactive and template-driven. Both capture user input events from the view, validate the user input, create a form model and data model to update, and provide a way to track changes.
-
Reactive forms provide direct, explicit access to the underlying forms object model. Compared to template-driven forms, they are more robust: they're more scalable, reusable, and testable. If forms are a key part of your application, or you're already using reactive patterns for building your application, use reactive forms.
-
Template-driven forms rely on directives in the template to create and manipulate the underlying object model. They are useful for adding a simple form to an app, such as an email list signup form. They're straightforward to add to an app, but they don't scale as well as reactive forms. If you have very basic form requirements and logic that can be managed solely in the template, template-driven forms could be a good fit.
Template Driven Forms
<form name="form" (ngSubmit)="tform.form.valid && onSubmit()" #tform="ngForm" novalidate>
<div class="form-group">
<label for="firstName">First Name</label>
<input
type="text"
class="form-control"
name="firstName"
[(ngModel)]="model.firstName"
#firstName="ngModel"
[ngClass]="{ 'is-invalid': tform.submitted && firstName.invalid }"
required
/>
<div *ngIf="tform.submitted && firstName.invalid" class="invalid-feedback">
<div *ngIf="firstName.errors.required">First Name is required</div>
</div>
</div>
<div class="form-group">
<button class="btn btn-primary">Register</button>
</div>
</form>
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss'],
})
export class AppComponent {
title = 'space-ng-templateforms'
model: any = {}
onSubmit() {
alert('SUCCESS!! :-)\n\n' + JSON.stringify(this.model))
}
}
Reactive Forms
import { Component } from '@angular/core';
import { FormControl } from '@angular/forms';
@Component({
selector: 'app-reactive-favorite-color',
template: `
Favorite Color: <input type="text" [formControl]="favoriteColorControl">
`
})
export class FavoriteColorComponent {
favoriteColorControl = new FormControl('');
}