代码之家  ›  专栏  ›  技术社区  ›  Bhavesh

Angular 2材质材质垫选择以编程方式打开/关闭

  •  20
  • Bhavesh  · 技术社区  · 8 年前

    有人知道如何通过编程打开或关闭mat select吗?作为pert-the-api,有打开和关闭的方法,但不知道如何从组件调用这些方法,而且现场没有任何示例显示这一点。

    谢谢

    3 回复  |  直到 8 年前
        1
  •  39
  •   Stefan Falk    7 年前

    为了访问这些属性,您需要标识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();
      }
    }
    

    View a working stackblitz here.

        2
  •  12
  •   Al Dass John Woo    7 年前

    另一种方法是在HTML端处理这一切,以避免将材质组件与typescript代码紧密耦合。

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

    干杯 丹

        3
  •  0
  •   Sam Berry    4 年前

    使用Angular 13和Angular Material 13,我必须单击“trigger”元素进行选择。

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

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

    组件中:

    @ViewChild("mySelect") mySelect;
    

    在模板中:

    <mat-select #mySelect ...
    
    推荐文章