Skip to main content

Setup

Do not forget to import ReactiveFormsModule in app.module.ts.

Reactive forms

Angular reactive forms are forms that are built programmatically in the component class. They are more flexible than template-driven forms.

Creating a form

import { Component } from '@angular/core';
import { FormBuilder } from '@angular/forms';

@Component({
selector: 'app-profile-editor',
templateUrl: './profile-editor.component.html',
styleUrls: ['./profile-editor.component.css'],
})
export class ProfileEditorComponent {
profileForm = this.fb.group({
firstName: [''],
lastName: [''],
address: this.fb.group({
street: [''],
city: [''],
state: [''],
zip: [''],
}),
});

constructor(private fb: FormBuilder) {}
}

Displaying the form

<form [formGroup]="profileForm" (ngSubmit)="onSubmit()">
<label>
First Name:
<input type="text" formControlName="firstName" />
</label>

<label>
Last Name:
<input type="text" formControlName="lastName" />
</label>

<div formGroupName="address">
<h3>Address</h3>

<label>
Street:
<input type="text" formControlName="street" />
</label>

<label>
City:
<input type="text" formControlName="city" />
</label>

<label>
State:
<input type="text" formControlName="state" />
</label>

<label>
Zip Code:
<input type="text" formControlName="zip" />
</label>
</div>

<button type="submit">Submit</button>
</form>

Submitting the form

onSubmit() {
console.warn(this.profileForm.value);
}

Setting the form value

this.profileForm.setValue({
firstName: 'Nancy',
lastName: 'Drew',
address: {
street: '123 Drew Street',
city: 'River Heights',
state: 'CA',
zip: '90210',
},
});

Updating parts of the form model

this.profileForm.patchValue({
firstName: 'Nancy',
address: {
street: '123 Drew Street',
},
});

Resetting the form

this.profileForm.reset();

Disabling the submit button

<button type="submit" [disabled]="!profileForm.valid">Submit</button>

Disabling the form

<form [formGroup]="profileForm" (ngSubmit)="onSubmit()" [disabled]="profileForm.disabled">

Disabling a form control

<input type="text" formControlName="firstName" [disabled]="profileForm.get('firstName').disabled" />

Form validation

profileForm = this.fb.group({
firstName: ['', Validators.required],
lastName: [''],
address: this.fb.group({
street: [''],
city: [''],
state: [''],
zip: [''],
}),
});
profileForm = this.fb.group({
firstName: ['', [Validators.required, Validators.pattern('^[a-zA-Z]+$')]],
lastName: [''],
address: this.fb.group({
street: [''],
city: [''],
state: [''],
zip: [''],
}),
});