angular - Material Angular 滚动到垫列表上的元素

标签 angular scroll angular-material material-design

我有一个包含多个元素的 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/

相关文章:

javascript - 在 Angular 规则中创建组件

javascript - 使用 LiveValidation 滚动到第一个表单错误

angular - 如何将 Angular Material 字段设置为宽度 :100%?

components - Angular 2 : how can component bind to class?

angular - 如何在 Angular Material 中设置图标的颜色?

angular - 如何在服务和指令脚本文件中使用 angular2 内置日期管道

ios - UIScrollView 在一个方向上被禁用 - iOS

iphone - 仅显示几张图像,滚动不顺畅

html - 使用 Angular-Material 进行简单的 CSS 修改

css - 如何更改固定标题的大小