In my angular project have angular material and use mat-select. Mat-select is the first element for my form in my case set auto focus while page was loaded successfully but I wasn't able to set auto focus on mat-select. Anyone can help me to find the way to set auto focus in mat-select.
@ViewChild("name") nameField: ElementRef;
ngOninit() {
this.nameField.nativeElement.focus();
}
html
<div>
<mat-select [(ngModel)]="nameField" #name>
<mat-option *ngFor="let option of options2" [value]="option.id">
{{ option.name }}
</mat-option>
</mat-select>
</div>
HTML :
<mat-select #someRef >
<mat-option *ngFor="let item of items;" [value]="item">
{{item.name}}
</mat-option>
</mat-select>
.ts : make sure you import MatSelect
import { MatSelect } from '@angular/material';
@ViewChild('someRef') someRef: MatSelect;
ngOnInit() {
if(this.someRef) this.someRef.focus();
}
Hope this helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With