Angular 14 Material Select Dropdown [Step-by-Step Guide]

To create a material dropdown in Angular, use the <mat-select> form control.

Angular material provides <mat-select> form control for selecting a value from a set of options, similar to the native <select> element. You can read more about selects in the Material Design spec.

To use angular material select, use <mat-select> formControl to select a value from the set of options.

It is designed to work inside of an <mat-form-field> element.

We can add options to the select by adding <mat-option> elements to the <mat-select>.

Each <mat-option> has a value property that can set the value that will be selected if a user chooses this option. In addition, the content of the <mat-option> will be shown to the user.

Here is the step-by-step guide to implement the material select dropdown.

Step 1: Create a new Angular project

ng new ang

Go inside the folder and open it in VSCode.

Step 2: Install and configure Angular Material.

Install hummer.js using the following command.

npm install --save hammerjs

Hammer.js is the optional dependency and helps with touch support for a few components.

Install Angular Material and Angular Animations using the following command.

npm install --save @angular/material @angular/animations @angular/cdk

Include hammerjs inside the angular.json file. You can find this file at the root of the project.

"scripts": [
     "./node_modules/hammerjs/hammer.min.js"
]

Step 3: Create a custom material module File.

Inside the src >> app folder, create one module file called material.module.ts.

Write the following code inside the material.module.ts file.

// material.module.ts

import { NgModule } from '@angular/core';

import { MatSelectModule, MatFormFieldModule, MatInputModule } from '@angular/material';

@NgModule({
  imports: [
    MatSelectModule,
    MatFormFieldModule,
    MatInputModule
  ],
  exports: [
    MatSelectModule,
    MatFormFieldModule,
    MatInputModule
  ]
})

export class MaterialModule { }

We imported MatSelectModule, MatFormFieldModule, MatInputModule.

The matInput is a directive that allows native <input> and <textarea> elements to work with <mat-form-field>.

The <mat-form-field> wraps several Angular Material components and applies common Text field styles such as the underline, floating label, and hint messages.

Here, we imported all the components in our Material Angular App. We can add other elements in the future if we need them.

This file is written on its own because it is easy to include all the Material components in this file, and later, this file will be imported inside the app.module.ts.

Step 4: Import a pre-built theme and Material icons

Angular Material comes with some pre-built themes. These themes have set off the colors and basic styling. The main available themes are indigo-pinkdeeppurple-amberpurple-green, and pink-bluegrey.

You can add the following code to your global styles.css file to import the theme. The file is inside the src folder.

@import '~@angular/material/prebuilt-themes/indigo-pink.css';

You can also access the Material Design icons and use named icons with the <mat-icon> component.

To import them to your project, you can add this to the head section of your project’s root index.html file.

<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">

Step 5: Import the material module file into the app module

We will import the following modules inside the app.module.ts file.

  1. FormsModule
  2. MaterialModule
  3. BrowserAnimationModule

Step 6: Build angular, select dropdown, and set value.

Write the following code inside the app.component.ts file.

// app.component.ts

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

export interface Brand {
  value: number;
  viewValue: string;
}

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  brands: Brand[] = [
    { value: 'Louis Vuitton', viewValue: 'Louis Vuitton' },
    { value: 'Gucci', viewValue: 'Gucci' },
    { value: 'Prada', viewValue: 'Prada' },
    { value: 'Chanel', viewValue: 'Chanel' },
  ];
}

In the above code, we created one Brand interface and added an array with values called brands.

So, the test data is of the Brand type, which has two properties.

  1. value
  2. viewValue

The value property’s value is what we need, and viewValues are displayed on the dropdown while you select.

So when the user selects any viewValue, behind the scenes, the value property is sent to the server.

We have four brands, and now we will display all those brands on the front end. So, add the following code inside the app.component.html file.

<!-- app.component.html -->

<h4>Basic mat-select</h4>
<mat-form-field>
  <mat-label>Favorite Brands</mat-label>
  <mat-select>
    <mat-option *ngFor="let brand of brands" [value]="brand.value">
      {{ brand.viewValue }}
    </mat-option>
  </mat-select>
</mat-form-field>

<h4>Basic native select</h4>
<mat-form-field>
  <mat-label>Brands</mat-label>
  <select matNativeControl required>
    <option *ngFor="let brand of brands" [value]="brand.value">
      {{ brand.viewValue }}
    </option>
  </select>
</mat-form-field>

We will display two select fields.

  1. Basic Material select dropdown
  2. Basic native select dropdown

We are using angular ngfor directive to render all the options of the select box and display them one by one with its values and viewValues.

Save the file and see the output.

Angular Dropdown menu

Step 7: Get and set the select value

Let’s get the value of the selected value by the user. First, add the following code inside the app.component.html file.

<!-- app.component.html -->

<h4>Basic mat-select</h4>
<mat-form-field>
  <mat-label>Favorite Brands</mat-label>
  <mat-select [(value)]="selected">
    <mat-option *ngFor="let brand of brands" [value]="brand.value">
      {{ brand.viewValue }}
    </mat-option>
  </mat-select>
</mat-form-field>
<p>You selected: {{selected}}</p>

Both<mat-select> and <select> support all of the form directives from the core FormsModule (NgModel) and ReactiveFormsModule (FormControl, FormGroup, etc.) As with native <select>, <mat-select> also supports a compareWith function.

Selecting an option

We get the value selected from the select dropdown.

Let’s add two select dropdowns and display both dropdowns’ selected values.

See the following code.

<!-- app.component.html -->

<h4>Basic mat-select</h4>
<mat-form-field>
  <mat-label>Favorite Brands</mat-label>
  <mat-select [(value)]="selected">
    <mat-option *ngFor="let brand of brands" [value]="brand.value">
      {{ brand.viewValue }}
    </mat-option>
  </mat-select>
</mat-form-field>
<p>You selected: {{selected}}</p>

<h4>Basic native select</h4>
<mat-form-field>
  <mat-label>Brands</mat-label>
  <select matNativeControl required [(ngModel)]="selectedValue">
    <option *ngFor="let brand of brands" [value]="brand.value">
      {{ brand.viewValue }}
    </option>
  </select>
</mat-form-field>
<p>You selected: {{selectedValue}}</p>

We use NgModel to bind the second selected dropdown’s value and display two-way data binding, as in Angular applications.

Save the file and see the output in the browser.
Get and set the select value

Angular Select Dropdown Validation

We can add validation on the select dropdown by adding simple angular forms. But before that, we need to import one more ReactiveForms module inside the app.module.ts file. So let’s import, and then we go ahead.

// app.module.ts

...
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
...

 imports: [
    ...
    FormsModule,
    ReactiveFormsModule,
    ...
  ],

You will face an error like the following if you do not add.

Can’t bind to ‘formControl’ since it isn’t a known property of ‘mat-select’.

While using formControl, you have to import ReactiveFormsModule to your imports array.

Add the following code inside the app.component.ts file.

// app.component.ts

import { Component } from '@angular/core';
import {FormControl, Validators} from '@angular/forms';
export interface Brand {
  value: string;
  viewValue: string;
}

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  brandControl = new FormControl('', [Validators.required]);
  selectFormControl = new FormControl('', Validators.required);
  brands: Brand[] = [
    { value: 'Louis Vuitton', viewValue: 'Louis Vuitton'},
    { value: 'Gucci', viewValue: 'Gucci'},
    { value: 'Prada', viewValue: 'Prada' },
    { value: 'Chanel', viewValue: 'Chanel' },
  ];
}

Write the following code inside the app.component.html file.

<!-- app.component.html -->

<h4>Basic mat-select</h4>
<mat-form-field>
  <mat-label>Favorite Brands</mat-label>
  <mat-select [formControl]="brandControl">
    <mat-option *ngFor="let brand of brands" [value]="brand.value">
      {{ brand.viewValue }}
    </mat-option>
  </mat-select>
  <mat-error *ngIf="brandControl.hasError('required')">Please choose a brand</mat-error>
</mat-form-field>
<p>You selected: {{selected}}</p>

<h4>Basic native select</h4>
<mat-form-field>
  <mat-label>Brands</mat-label>
  <select matNativeControl required [(ngModel)]="selectedValue">
    <option *ngFor="let brand of brands" [value]="brand.value">
      {{ brand.viewValue }}
    </option>
  </select>
  <mat-error *ngIf="selectFormControl.hasError('required')">
    This field is required
  </mat-error>
</mat-form-field>
<p>You selected: {{selectedValue}}</p>

Here, we put the NgIf condition; if the user does not select an option, we display the error.

Save the file and see the output.

Angular Select Dropdown Validation

That’s it!

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.