angularangular-material2md-select

Angular 2 material mat-select programmatically open/close


Does any one know how to programmatically open or close mat-select? As pert the api there are methods for open and close but don't know how to call those methods from component and there isn't any example showing that on site.

Thanks


Solution

  • In order to access these properties you need to identify the DOM element and access it with a ViewChild:

    component.html

      <mat-select #mySelect placeholder="Favorite food">
        <mat-option *ngFor="let food of foods" [value]="food.value">
          {{ food.viewValue }}
        </mat-option>
      </mat-select>
    

    component.ts

    import {Component, ViewChild} from '@angular/core';
    
    @Component({
      selector: 'select-overview-example',
      templateUrl: 'select-overview-example.html',
      styleUrls: ['select-overview-example.css'],
    })
    export class SelectOverviewExample {
      @ViewChild('mySelect') mySelect;
      foods = [
        {value: 'steak-0', viewValue: 'Steak'},
        {value: 'pizza-1', viewValue: 'Pizza'},
        {value: 'tacos-2', viewValue: 'Tacos'}
      ];
    
      click() {
        this.mySelect.open();
      }
    }
    

    View a working stackblitz here.