Angular 2 material mat-select programmatically open/close

不羁岁月 提交于 2020-01-02 01:16:14

问题


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


回答1:


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.




回答2:


Another approach, so as not to so tightly couple the material component to your typescript code would be to handle this all on the HTML side.

<mat-form-field>
  <mat-select #mySelect placeholder="Favorite food">
    <mat-option *ngFor="let food of foods" [value]="food.value">
      {{ food.viewValue }}
    </mat-option>
  </mat-select>
</mat-form-field>
<br/>
<button (click)="mySelect.toggle()">click</button>

I used toggle() on the "selected" answer to both open or close the panel, although you can substitute open() or close() calls depending on your needs.

The key piece seems to be that template variable (#mySelect) that I learned thanks to the answer that @zbagley provided. I just kept tinkering to make it work without the tight binding of a @ViewChild.

Cheers, Dan



来源:https://stackoverflow.com/questions/47878480/angular-2-material-mat-select-programmatically-open-close

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!