Issue
I am using Angular material for a drop down view. Here is my HTML:
<mat-form-field class="vertical-center" subscriptSizing="dynamic" #myFormField>
<mat-label>Style</mat-label>
<mat-select [ngModel]="selectedStyle" name="styles" (ngModelChange)="onStyleChange($event)">
<ng-container *ngFor="let style of styles; ">
<mat-option [value]="style.value">{{ style.viewValue }}</mat-option>
</ng-container>
</mat-select>
</mat-form-field>
How can I remove the focus during the (ngModelChange)="onStyleChange($event)"
event?
I tried the below options with no success
- Directly Blur the mat-select Element
- Focus on Another Element
- Trigger a Click on a Different Element
- Using Angular Focus Trap
Solution
Using the close
function of mat-select
seems to remove the focus!
import { Component } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import 'zone.js';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatSelect, MatSelectModule } from '@angular/material/select';
import { FormsModule } from '@angular/forms';
import { CommonModule } from '@angular/common';
import { provideAnimations } from '@angular/platform-browser/animations';
@Component({
selector: 'app-root',
standalone: true,
template: `
<mat-form-field class="vertical-center" subscriptSizing="dynamic" #myFormField>
<mat-label>Style</mat-label>
<mat-select #matSelect [ngModel]="selectedStyle" name="styles" (ngModelChange)="onStyleChange($event, matSelect)">
<ng-container *ngFor="let style of styles; ">
<mat-option [value]="style.value">{{ style.viewValue }}</mat-option>
</ng-container>
</mat-select>
</mat-form-field>
`,
imports: [MatFormFieldModule, MatSelectModule, FormsModule, CommonModule],
})
export class App {
selectedStyle = null;
styles = [
{ value: 'test1', viewValue: 'Test1' },
{ value: 'test2', viewValue: 'Test2' },
{ value: 'test3', viewValue: 'Test3' },
{ value: 'test4', viewValue: 'Test4' },
];
onStyleChange(event: any, matSelect: MatSelect) {
this.selectedStyle = event;
matSelect.close();
}
}
bootstrapApplication(App, {
providers: [provideAnimations()],
});
Answered By - Naren Murali
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.