首页 > 解决方案 > 在 Angular 门户中保持滚动状态

问题描述

我遇到了角度门户的问题:我有一个包含门户的页面和一些更改门户内容的触发器。都好。当门户更改其内容时,它会将渲染(门户内部)组件的变量保存在内存中,例如增量;但遗憾的是滚动位置不是:每次门户更改时,滚动都会回到顶部。

有谁知道如何解决这个问题?

我在这里重现了这个问题StackBlitz

标签: angularscrollportal

解决方案


在你的小部件中试试这个:

import { CdkScrollable } from "@angular/cdk/overlay";
import {
  AfterViewChecked,
  AfterViewInit,
  Component,
  ElementRef,
  Input,
  OnDestroy,
  ViewChild
} from "@angular/core";

@Component({
  selector: "tab2",
  template: `
    <portal>
      <div
        #scrollitem
        cdkScrollable
        *ngIf="target == 2"
        style="border-style: solid; height:200px; overflow: auto"
      >
        <p>Value: {{ tab2Value }}</p>
        <button (click)="increment()">INCREMENT</button>
        <p>INSIDE PORTAL: TAB2</p>
        <p>INSIDE PORTAL: TAB2</p>
        <p>INSIDE PORTAL: TAB2</p>
        <p>INSIDE PORTAL: TAB2</p>
        <p>INSIDE PORTAL: TAB2</p>
        <p>INSIDE PORTAL: TAB2</p>
        <p>INSIDE PORTAL: TAB2</p>
        <p>INSIDE PORTAL: TAB2</p>
        <p>INSIDE PORTAL: TAB2</p>
        <p>INSIDE PORTAL: TAB2</p>
        <p>INSIDE PORTAL: TAB2</p>
        <p>INSIDE PORTAL: TAB2</p>
        <p>INSIDE PORTAL: TAB2</p>
        <p>INSIDE PORTAL: TAB2</p>
        <p>INSIDE PORTAL: TAB2</p>
        <p>INSIDE PORTAL: TAB2</p>
        <p>INSIDE PORTAL: TAB2</p>
        <p>INSIDE PORTAL: TAB2</p>
        <p>INSIDE PORTAL: TAB2</p>
      </div>
    </portal>
  `,
  styles: []
})
export class Tab2 implements AfterViewChecked, OnDestroy {
  @Input() target: number;

  @ViewChild("scrollitem", { read: CdkScrollable }) scrollitem: CdkScrollable;

  tab2Value = 0;

  scrolltop = 0;

  subs = null;

  constructor() {}
  ngOnDestroy(): void {
    if (this.subs) {
      this.subs.unsubscribe();
    }
  }

  ngAfterViewChecked(): void {
    if (this.scrollitem) {
      this.scrollitem.scrollTo({ top: this.scrolltop });

      this.subs = this.scrollitem.elementScrolled().subscribe(o => {
        this.scrolltop = this.scrollitem.measureScrollOffset("top");
      });
    }
  }

  increment() {
    this.tab2Value++;
  }
}

Stackblitz 在这里: https ://stackblitz.com/edit/angular-ivy-2uaxdz?file=src%2Fapp%2Ftab2.component.ts


推荐阅读