'Focus a specific mat-option item when mat-select dialog is opened?
I want to focus to an option(scroll to an option) automatically when mat-select is opened. I thought that with a little bit of search this will be solved easily but I couldn't found a solid answer anywhere.
Here is the mat-select that I use.
<mat-select required name="AngabeId" [(ngModel)]="bedingungszielList[0]?.BedingungenList[i].AngabeId">
<ng-container *ngFor="let antragsbereich of antragsBereichListWithAngabelist">
<mat-optgroup *ngIf="antragsbereich.AngabeList.length > 0" [label]="antragsbereich.Bezeichnung" class="bedigungOptGroup">
<ng-container *ngFor="let angabe of antragsbereich.AngabeList">
<mat-option *ngIf="angabe.Id !== Id" [value]="angabe.Id" class="bedigungOptions">
{{ angabe.Fragetext }}
</mat-option>
</ng-container>
</mat-optgroup>
</ng-container>
</mat-select>
And here is some sample code of what I whant to achieve, angabe.Id being the mat-option ngmodel.
this.antragsBereichListWithAngabelist.forEach(element => {
element.AngabeList.forEach(angabe => {
if(angabe.Id===962)
angabe.Id.focus(); // mat-option focus, my intention, sample code(bad)
});
});
Here's the example with image: mat-option focus
Solution 1:[1]
If I understand your problem, you wanted to focus a option when you open select box. So, I would suggest you to use (opened) event in mat-select. This is something I tried:
.html
<mat-form-field>
<mat-label>Cars</mat-label>
<mat-select [(ngModel)]="default" required (opened)="selectOpened()">
<mat-option value="volvo">Volvo</mat-option>
<mat-option value="saab">Saab</mat-option>
<mat-option value="mercedes">Mercedes</mat-option>
<mat-option value="audi">Audi</mat-option>
</mat-select>
</mat-form-field>
.ts
default = '';
selectOpened() {
this.default = 'audi';
}
This code will focus audi option when select box is opened. Hope this is useful for you.
Solution 2:[2]
For anyone that might have the same problem, combined with Maruthi Eranki answer this is what I came up with..
selectOpened() {
document.querySelectorAll('.bedigungOptGroup').forEach(item=>{
if(item.getAttribute("antragsId") ===
this.antragsBereichValueSelected.toString())
item.scrollIntoView(true);
});
}
Solution 3:[3]
The simple answer is get that mat-option element and then use the scrollIntoview funtion, please check this docs
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Maruthi Eranki |
Solution 2 | Çlirim Murati |
Solution 3 | bugMaker |