Angular Material Select | Dropdowns in Angular


How to use Angular Material Select ? Dropdowns in Angular.

Create an angular app using the angular cli.

ng new angular-select

Once you have the Angular application, install Angular Material to your application.

Next, import the MatSelectModule to your app.module.ts file.

import { MatSelectModule } from  '@angular/material/select';

Also make sure to add FormsModule if you plan to use ngModel.

import { FormsModule } from  '@angular/forms';

Import FormsModule and MatSelectModule to the imports array in app.module.ts. Here is how app.module.ts file looks :

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { MatSelectModule } from '@angular/material/select';
import { FormsModule } from '@angular/forms';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    FormsModule,
    BrowserAnimationsModule,
    MatSelectModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Open your component html file app.component.html and add the following code:

<mat-select placeholder="Select price" [(ngModel)]="selectedValue" name="item">
  <mat-option *ngFor="let item of items" [value]="item.value">
    {{item.viewValue}}
  </mat-option>
</mat-select>

Add the items array and the selectedValue in the app.component.ts file:

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  selectedValue: any;

  items = [{
    value : 100,
    viewValue : 100
  },{
    value : 200,
    viewValue : 200
  },{
    value : 300,
    viewValue : 300
  }];
  
}

Save the changes and run the app. You will be able to see the Angular Material Select. On material select selection, the value is available in the variable selectedValue.