<button mat-button id="categories-button" [mat-menu-trigger-for]="categoryList">
<span>categories</span>
<mat-icon id="drop-arrow">arrow_drop_down</mat-icon>
</button>
<mat-menu #categoryList>
<mat-form-field appearance="standard" id="category-search-wrapper">
<input (click)="$event.stopPropagation()" matInput id="category-search">
</mat-form-field>
<button mat-menu-item>Settings</button>
<button mat-menu-item>Help</button>
</mat-menu>
我希望category-search
输入的焦点,当打开Menu时,问题是,在发出menuOpened事件时,它似乎还没有准备好。打开菜单后如何聚焦输入元素?
答案 0 :(得分:1)
<button id="categories-button" [mat-menu-trigger-for]="categoryList" (menuOpened)="this.categoryListOpened()">
<span>categories</span>
<mat-icon id="drop-arrow">arrow_drop_down</mat-icon>
</button>
<mat-menu #categoryList>
<mat-form-field appearance="standard" id="category-search-wrapper">
<input matInput id="category-search" (click)="$event.stopPropagation()">
</mat-form-field>
<button mat-menu-item>Settings</button>
<button mat-menu-item>Help</button>
</mat-menu>
categoryListOpened() {
setTimeout(() => {
this.categorySearch.focus();
});
}
(menuOpened)="this.categoryListOpened()"
,以打开菜单categoryListOpened
方法答案 1 :(得分:1)
您可以按照以下方式使用ViewChild
<button mat-button
(menuOpened)="menuOpened()"
[matMenuTriggerFor]="menu">Menu
</button>
<mat-menu #menu="matMenu">
<mat-form-field appearance="standard" id="category-search-wrapper">
<input
#search
(click)="$event.stopPropagation()" matInput>
</mat-form-field>
<button mat-menu-item>Item 1</button>
<button mat-menu-item>Item 2</button>
</mat-menu>
export class AppComponent {
@ViewChild('search', {static: false})
inputElement: ElementRef;
menuOpened() {
setTimeout(() => {
this.inputElement.nativeElement.focus();
}, 0);
}
}