Binding Angular Material Select to a Reactive Form Control

Ole Ersoy
2 min readMar 12, 2021

Updated Version

Scenario

We have a reactive form control:

control:FormControl = new FormControl('steak-0')

And we want to bind it to our mat-select element such that we can:

  • Receive reactive notifications from control.valueChanges
  • Have the mat-select default value be steak-0

Approach

Within the app.module.ts we have imported both FormsModule and ReactiveFormsModule as these are necessary.

In the below app.component.ts component we have created an control:FormControl instance and initialized the value to steak-0 .

import { Component, VERSION } from "@angular/core";
import { FormControl } from "@angular/forms";
interface Food {
value: string;
viewValue: string;
}
@Component({
selector: "my-app",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent {
control = new FormControl("steak-0");
foods: Food[] = [
{ value: "steak-0", viewValue: "Steak" },
{ value: "pizza-1", viewValue: "Pizza" },
{ value: "tacos-2", viewValue: "Tacos" }
];
constructor() {
this.control.valueChanges.subscribe(s => {
console.log(`The selected value is ${s}`);
});
}
}

In the app.component.html we have two declarations of mat-select . The first one does not bind to control . As can be seen the mat-select uses the <mat-label>Favorite food</mat-label> as the place holder instruction telling the user to select a food in this case.

In the second case the mat-select value is initialized to steak-0.

We subscribe to the form control within the app.component.ts constructor.

this.control.valueChanges.subscribe(s => {
console.log(`The selected value is ${s}`);
});

Whenever we change the selection, the subscription logs the selected value.

Demo

--

--