[英]How to focus() on Expansion Panel in a loop in Angular Material?
我在一个循环中有一系列 Angular 材料扩展面板。 当用户单击给定面板时,我希望该面板成为页面上的焦点。
我怎样才能做到这一点?
这是我尝试过的(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()
}
}
这将打开面板,并且此代码在单击的面板上正确注册了一个单击事件,但 focus() 似乎什么都不做——相关面板没有成为焦点。
因此,例如,如果面板在您单击时已经位于页面底部,则会向下打开,因此面板详细信息隐藏在页面“下方”。 我想确保您始终可以看到任何点击面板的详细信息。
编辑:也许“focus()”在这里不是正确的想法。 我的目标是将点击的面板垂直居中在页面上——以确保它在被点击后始终可见。 有没有办法做到这一点?
scrollIntoView() 方法将指定元素滚动到浏览器可见区域 window
clicked(i){
this.focusOnThisPanel.toArray()[i].nativeElement.scrollIntoView({ behavior: 'smooth' });
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.