在 Angular 个门户中保持滚动状态

Keep scrolling status in Angular portals

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

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

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

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

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