19

有谁知道如何以编程方式打开或关闭 mat-select?根据 api,有打开和关闭的方法,但不知道如何从组件调用这些方法,并且现场没有任何示例显示。

谢谢

4

3 回答 3

38

为了访问这些属性,您需要识别 DOM 元素并使用ViewChild:

组件.html

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

组件.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();
  }
}

在此处查看有效的堆栈闪电战。

于 2017-12-19T00:55:10.813 回答
12

另一种方法是在 HTML 端处理这一切,以免将材料组件与您的打字稿代码如此紧密地耦合。

<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>

toggle()在“选定”答案上使用了打开或关闭面板,尽管您可以根据需要替换open()或调用。close()

关键部分似乎是#mySelect我通过@zbagley 提供的答案了解到的模板变量 ( )。我只是不断修补以使其在没有紧密绑定的情况下工作@ViewChild

干杯,丹

于 2018-04-27T18:59:26.620 回答
0

使用 Angular 13 和 Angular Material 13,我必须单击选择的“触发器”元素。

this.mySelect.trigger.nativeElement.click();

(下面的配置与其他答案相同)

在组件中:

@ViewChild("mySelect") mySelect;

在模板中:

<mat-select #mySelect ...
于 2021-12-08T18:26:26.607 回答