Reputation: 895
<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>
I want category-search
input to be focused, when Menu is opened, the problem is it doesn't seem to be ready yet, when menuOpened event is emitted. How can I focus input element when Menu is opened?
Upvotes: 3
Views: 6129
Reputation: 895
<button
id="categories-button"
[mat-menu-trigger-for]="categoryList"
(menuOpened)="categorySearch.focus()"
>
<span>categories</span>
<mat-icon id="drop-arrow">arrow_drop_down</mat-icon>
</button>
<mat-menu #categoryList>
<mat-form-field #categorySearch appearance="standard" id="category-search-wrapper">
<input matInput (click)="$event.stopPropagation()" />
</mat-form-field>
<button mat-menu-item>Settings</button>
<button mat-menu-item>Help</button>
</mat-menu>
(menuOpened)="this.categoryListOpened()"
to the button, that opens the MenucategoryListOpened
method in your component's class like aboveUpvotes: 3
Reputation: 2795
you can use ViewChild
as follow
<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);
}
}
Upvotes: 3