如何将div的滚动条移动到垫子选择列表中的某个选项



我希望能够在单击时将滚动条滚动到特定选项。现在,我知道如何以一种不恰当的方式来实现这一点,即访问MatListOption类的私有成员变量,但这当然是错误的方式。还有其他方法吗?同样,下面的代码确实按预期工作,但这当然是错误的做法

对于scs,#容器有一个高度并溢出-y:auto以获得滚动条。

属性"_element"是私有的,只能在类"MatListOption"中访问。

@ViewChild('list') list: MatSelectionList;
public taskTypeAreas: ITask[] = [
{name: "Area 1"},
{name: "Area 2"},
...
{name: "Area 20"}
]

public scrollToArea(area: string){
const topPos = this.list.options.find(v => v.value === area)._element.nativeElement.offsetTop;
document.getElementById("container").scrollTop = topPos - 10;
}
<div id="container">
<mat-selection-list #list [(ngModel)]="selectedOptions">
<mat-list-option *ngFor="let tta of taskTypeAreas" [value]="tta.name">
{{tta.name}}
</mat-list-option>
</mat-selection-list>
</div>
<div><button (click)="scrollToArea('Area 8')">Area</button></div>

https://stackblitz.com/edit/material-selection-list-5-0-0-dfywbi?file=app/app.component.ts

我不得不对此进行更多的研究,并找到了一种名为"_getHostElement(("在那里我可以访问.offsetTop的属性。所以答案如下。除非有更好的解决方案,否则如果没有更好的解决办法,我会接受自己的答案。

public scrollToArea(area: string){
const topPos = this.list.options.find(v => v.value === area)._getHostElement().offsetTop;
document.getElementById("container").scrollTop = topPos - 10;
}

最新更新