[英]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.