Initializing Your Angular Reactive Form | Task

Ole Ersoy
Nov - 28  -  1 min

Scenario

We have a form that captures a Todo title and description values.

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();
}

Demo