Issue
I have a series of Angular Material expansion panels in a loop. When a user clicks on a given panel, I want that panel to be the focus on the page.
How can I do this?
This is what i've tried (Angular 8):
html:
<mat-accordion>
<mat-expansion-panel *ngFor="let panel of panels; let i = index" >
<mat-expansion-panel-header>
<mat-panel-title>
<div (click)="clicked(i)">
{{panel.Header}}
</div>
</mat-panel-title>
</mat-expansion-panel-header>
<div #focusOnThisPanel>{{panel.details}}</div>
</mat-expansion-panel>
</mat-accordion>
ts:
import { Component, OnInit, ElementRef, ViewChildren, QueryList} from '@angular/core';
public panelElements: any
export class GreatComponent implements OnInit {
@ViewChildren('focusOnThisPanel') focusOnThisPanel: QueryList<ElementRef>
constructor() {}
ngAfterViewInit(){
this.panelElements = this.focusOnThisPanel.map(panel => {
return panel.nativeElement;
})
}
clicked(i){
this.panelElements[i].focus()
}
}
This opens the panel, and this code properly registers a click event on the clicked-on panel, but the focus() seems to do nothing--the relevant panel does not come into focus.
So, for example, if the panel was already at the bottom of the page when you click it, it opens down, so the panel details are hidden "below" the page. I want to be sure you can always see the details of any clicked-on panel.
EDIT: Maybe "focus()" is not the right idea here. My goal is to center the clicked on panel vertically on the page--to make sure that it is always visible after it has been clicked. Is there a way to do that?
Solution
Try scrollIntoView
The scrollIntoView() method scrolls the specified element into the visible area of the browser window
clicked(i){
this.focusOnThisPanel.toArray()[i].nativeElement.scrollIntoView({ behavior: 'smooth' });
}
Answered By - Chellappan வ
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.