【问题标题】:Angular 2 material mat-select programmatically open/closeAngular 2材料垫选择以编程方式打开/关闭
【发布时间】:2018-06-01 09:17:36
【问题描述】:

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

谢谢

【问题讨论】:

    标签: angular angular-material2 md-select


    【解决方案1】:

    为了访问这些属性,您需要识别 DOM 元素并使用 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.

    【讨论】:

    • 我收到错误:无法读取未定义的属性“打开”
    • @SolomonRaja 如果mat-select 在 DOM 中不可用,这通常会发生。确保在视图初始化后进行任何.open() 调用(在构造函数、OnInit 等中不可用)。确保没有 *ngIf 或类似内容导致它也不会在 DOM 中呈现。
    • 感谢您的回复。我什至在提到的 stackblitz 示例中遇到了这个错误。如果我犯了任何错误,请帮助我
    • @SolomonRaja 抱歉,但在运行默认的 stackblitz 时,我没有在多个浏览器中看到任何问题。我能想到的只是试图将mySelect 定义为 MatSelect:@ViewChild('mySelect') mySelect: MatSelect;
    【解决方案2】:

    另一种方法是在 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() 调用。

    关键部分似乎是我通过@zbagley 提供的答案了解到的模板变量(#mySelect)。我一直在努力让它在没有@ViewChild 的紧密绑定的情况下工作。

    干杯, 丹

    【讨论】:

      【解决方案3】:

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

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

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

      在组件中:

      @ViewChild("mySelect") mySelect;
      

      在模板中:

      <mat-select #mySelect ...
      

      【讨论】: