我有一个包含多个元素的 Angular Material 列表,可以选择其中之一。
当我加载此列表时,我想将列表向上滚动到所选元素,以使其更加可见。有什么选择吗?
我正在考虑在 ngOnInit 中检查是否选择了项目,但我真的不知道如何将此列表向上滚动到该项目。
注意:不应滚动整个页面,仅应滚动列表中的元素。
组件.html
<mat-nav-list>
<mat-list-item *ngFor="let item of items" (click)="itemClick(item)"
[ngClass]="item.selectedClass">
{{item.someValue}}
</mat-list-item>
</mat-nav-list>
组件.ts
private itemClick(item: Item): Observable<any> {
if (item) {
this.something = item;
this.items.forEach(item => {
if (item && item.name === item.name) {
item["selectedClass"] = "item-selected";
} else {
item["selectedClass"] = undefined;
}
});
} else {
this.something = null;
this.items.forEach(item => {
item["selectedClass"] = undefined;
});
}
return of(null);
}
最佳答案
查看此演示:https://stackblitz.com/edit/angular-yjbpoq?file=src%2Fapp%2Fhello.component.ts
要点是您将一个新指令附加到您的列表和每个列表项:
<mat-list appScrollable ...>
<mat-list-item appOffsetTop ...>
...
</mat-list-item>
</mat-list>
列表中的人可以设置列表的scrollTop
(或使用scrollTo
,或其他):
@Directive({selector: '[appScrollable]'})
export class ScrollableDirective {
constructor(private _el: ElementRef) {}
set scrollTop(value: number) { this._el.nativeElement.scrollTop = value; }
}
列表项中的一项可以报告其 offsetTop
:
@Directive({ selector: '[appOffsetTop]'})
export class OffsetTopDirective {
constructor(private _el: ElementRef) { }
get offsetTop(): number { return this._el.nativeElement.offsetTop; }
}
通过 @ViewChild
和 @ViewChildren
在组件中访问每种类型的指令:
@ViewChildren(OffsetTopDirective) listItems: QueryList<OffsetTopDirective>;
@ViewChild(ScrollableDirective) list: ScrollableDirective;
在 AfterViewInit
生命周期 Hook 中,将在项目列表中搜索与当前所选项目匹配的项目(出于说明目的,此处随机设置)。然后将列表的 scrollTop
设置为该项目的 offsetTop
:
// Inside your component
selectedItem = Math.floor(Math.random() * 500);
items = new Array(500).fill(0).map((_, i) => `Item ${i}`);
ngAfterViewInit() {
this.list.scrollTop = this.listItems.find((_, i) => i === this.selectedItem).offsetTop;
}
关于angular - Material Angular 滚动到垫列表上的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54310902/