angular - 在 Angular 门户中保持滚动状态
问题描述
我遇到了角度门户的问题:我有一个包含门户的页面和一些更改门户内容的触发器。都好。当门户更改其内容时,它会将渲染(门户内部)组件的变量保存在内存中,例如增量;但遗憾的是滚动位置不是:每次门户更改时,滚动都会回到顶部。
有谁知道如何解决这个问题?
我在这里重现了这个问题StackBlitz:
- 点击“设置为 2”
- 单击增量并向下滚动
- 单击“设置为<2以外>
- 点击“设置为 2”
- 查看您的最后一个增量,但滚动位于顶部而不是您离开的位置
解决方案
在你的小部件中试试这个:
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
推荐阅读
- javascript - 如何使用最少的临时变量将 JS 代码解析为每行一个操作?
- angular - Angular:移动组件的宿主元素
- java - 未找到 Log4J 属性/无效
- python - 使用 GEKKO(二阶微分方程)的估计参数
- c# - 使用 CefSharp 的 Foreach 循环不会移动到下一个站点
- python - minimum_rotated_rectangle 中的角度
- azure-devops - 如何使用 Azure DevOps Service Hooks 收到有关在 YAML 管道中完成的部署的通知?
- javascript - 似乎 React 在 useeffect (Reask) 中状态更新后没有重新渲染
- opengl - 将 mix() 应用于具有 Alpha 通道的纹理会导致伪影
- javafx - 如何在 NetbeansIDE 11.3 中启用 JavaFX