Angular 2 material mat-select 以编程方式 open/close
Angular 2 material mat-select programmatically open/close
有谁知道如何以编程方式打开或关闭 mat-select?根据 api,有打开和关闭的方法,但不知道如何从组件调用这些方法,并且现场没有任何示例显示。
谢谢
为了访问这些属性,您需要识别 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();
}
}
为了不将 material 组件与您的打字稿代码紧密耦合,另一种方法是在 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>
我在 "selected" 的回答中使用 toggle()
打开或关闭面板,尽管您可以根据需要替换 open()
或 close()
调用。
关键部分似乎是我从@zbagley 提供的答案中了解到的模板变量 (#mySelect
)。我一直在修补,让它在没有 @ViewChild
.
的紧密绑定的情况下工作
干杯,
旦
使用 Angular 13 和 Angular Material 13,我必须单击 select 的“触发”元素。
this.mySelect.trigger.nativeElement.click();
(以下配置与其他答案相同)
在组件中:
@ViewChild("mySelect") mySelect;
在模板中:
<mat-select #mySelect ...
有谁知道如何以编程方式打开或关闭 mat-select?根据 api,有打开和关闭的方法,但不知道如何从组件调用这些方法,并且现场没有任何示例显示。
谢谢
为了访问这些属性,您需要识别 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();
}
}
为了不将 material 组件与您的打字稿代码紧密耦合,另一种方法是在 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>
我在 "selected" 的回答中使用 toggle()
打开或关闭面板,尽管您可以根据需要替换 open()
或 close()
调用。
关键部分似乎是我从@zbagley 提供的答案中了解到的模板变量 (#mySelect
)。我一直在修补,让它在没有 @ViewChild
.
干杯, 旦
使用 Angular 13 和 Angular Material 13,我必须单击 select 的“触发”元素。
this.mySelect.trigger.nativeElement.click();
(以下配置与其他答案相同)
在组件中:
@ViewChild("mySelect") mySelect;
在模板中:
<mat-select #mySelect ...