Initializing Your Angular Reactive Form

Ole Ersoy
Dec 24, 2019

--

Image by TeroVesalainen from Pixabay

‘Updated Version

There is an updated version of this article here:

Scenario

We have a form that captures a Todo title and description . We want to edit Todo instances, and therefore we need to initialize the form with the instance.

Approach

Implement the form in the AppComponent :

form: FormGroup = new FormGroup({
title: new FormControl(''),
description: new FormControl('')
})

Create the markup in app.component.html :

<form [formGroup]='form'><mat-form-field>
<input matInput placeholder="Title"
formControlName="title">
</mat-form-field>
<mat-form-field>
<input matInput placeholder="Description"
formControlName="description">
</mat-form-field>
</form>

Initialize form :

initializeForm() {
this.form.setValue({
title: 'Complete me',
description: 'Now!'
})
}
ngOnInit() {
this.initializeForm();
}

--

--