AppDividend
Latest Code Tutorials

Angular 12 Material Select Dropdown Example For Beginners

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 for selecting a value from the set of options.

Angular Material components will help us build attractive UI and UX, consistent and functional web pages, and web applications while keeping to modern web design principles like browser portability and compatibility, device independence, and graceful degradation.

Select dropdown in HTML

HTML <select> tag is used to create a dropdown list of options, which appears when clicking on the form element and allows the user to choose one of the options.

The <option> tag is used to define the possible options to choose from. The tag is put into <select> tag.

The first option from the options’ list is selected by default. To change the chosen predefined option, the attribute is used.

The <optgroup> tag is used to group several options into one group. The content of <optgroup> looks like heading in bold.

The look of the list depends on the onsize attribute, which defines the height of the list. The width of the list depends on the length of the text inside the <option> tag. The width can be regulated with CSS styles, as well.

Angular Material Select Dropdown

The Angular Material library offers many components. We have covered the following components in this blog.

  1. Angular material table
  2. Angular material modal
  3. Angular material icon

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. The content of the <mat-option> is what will be shown to the user.

Angular Material also supports use of the native <select> element inside of <mat-form-field>. The native control has several performance, accessibility, and usability advantages.

In this Angular Material select dropdown example, we will use the Angular Material library to construct UI/UX.

Okay, let’s start Angular Material select dropdown example step by step.

Step 1: Create a new Angular project

I assume that you have the latest Angular CLI. Type the following command.

ng new ang

Go inside the folder and open the folder in VSCode.

Step 2: Install and configure Angular Material.

First, 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 of the components.

Now, install Angular Material and Angular Animations using the following command.

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

Now, 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.

Okay, now, 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 have imported MatSelectModule, MatFormFieldModule, MatInputModule.

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

The <mat-form-field> is used to wrap several Angular Material components and apply common Text field styles such as the underline, floating label, and hint messages.

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

The reason this file is written on its own is that 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.

To import the theme, you can add the following code to your global styles.css file. 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 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

We need FormsModule because we are working with the Angular forms, and angular select dropdown is part of the form, so we need to import the module.

Then we have imported the newly create Material Module, and then we need to import BrowserAnimationModule.

Animation provides the illusion of motion: HTML elements change styling over time.

Well-designed animations can make your application more fun and easier to use, but they aren’t just cosmetic. Instead, animations can improve your app and user experience in several ways.

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 have created one interface called Brand and add 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 one by one with its values and viewValues.

Save the file and see the output.

Angular 8 Select Dropdown Example

Step 7: Get and set the select value

The <mat-select> supports two-way binding to the value property without the need for Angular forms.

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.

Angular Material Select

So, 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 are using NgModel to bind the second selected dropdown’s value and display using two-way data binding, as we generally do in Angular application.

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

Angular Select Dropdown Validation Example

We can add validation on select dropdown the same as we have added on simple angular forms.

But before that, we need to import one more module called ReactiveForms 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,
    ...
  ],

If you do not add, then you will face an error like the following.

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.

Now, 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' },
  ];
}

There are a number of <mat-form-field> features that can be used with both <select> and <mat-select>. These include error messages, hint text, prefix & suffix, and themes.

We have put the validation that if we find those two select form values empty, we raise the error and display it on the frontend.

At last, 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 have put the NgIf condition; if the user does not select an option, we will display the error.

Save the file and see the output.

Angular Select Dropdown Validation Example

Conclusion

In this Angular Material select dropdown example, we have seen how to set up material design in angular, how to import modules, and how to work with forms and validation and especially <mat-select> directive.

Select box, radio button, file upload, multi-select, checkbox, and so on. All these components are beneficial to create an interactive web application.

Finally, Angular Material Select Dropdown Example is over.

See also

Angular Forms

Angular checkbox

Angular Material checkbox

Angular Material Icons

Angular Radio Button

Leave A Reply

Your email address will not be published.

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