gpt4 book ai didi

当我被路由到所需位置时,Angular viewportScroller 第一次不工作#fragment

转载 作者:行者123 更新时间:2023-12-05 07:26:01 26 4
gpt4 key购买 nike

我遇到标题中提到的 viewportScroller 的问题。

在我的项目中,我需要从一个嵌套的 url 重定向到一个简单的静态条款和条件网站(它有一个导航侧边栏,可以在网站内导航到每个 anchor )。

效果很好,但一开始并没有滚动到所需的片段。如果您访问上述条款和条件网站并再次执行整个工作流程(转到嵌套 url-> 单击将您重定向到条款网站的链接),那么它会将您带到所需的片段。而且它不允许我使用导航栏滚动到同一个片段两次。

重定向您的链接:

<a routerLink="/terms-and-conditions"
fragment="practice-customer-key-obligations">Terms and Conditions</a>

条款组件:

import { Component, OnInit, AfterViewChecked } from '@angular/core';
import { Router, Scroll } from '@angular/router';
import { ViewportScroller } from '@angular/common';
import { filter } from 'rxjs/operators';
@Component({
selector: 'app-terms-and-conditions',
templateUrl: './terms-and-conditions.component.html',
styleUrls: ['./terms-and-conditions.component.scss']
})
export class TermsAndConditionsComponent implements OnInit, AfterViewChecked {

constructor(private router: Router, private viewportScroller: ViewportScroller) {
}

ngOnInit() {

}

ngAfterViewChecked() {
this.viewportScroller.setOffset([0, 64]);
this.viewportScroller.setHistoryScrollRestoration('auto');

this.router.events.pipe(filter(element => element instanceof Scroll)).subscribe((element: any) => {
this.viewportScroller.scrollToAnchor(element.anchor);
});
}
}

术语路由模块:

import { CommonModule } from '@angular/common';
import { NgModule } from '@angular/core';
import { RouterModule, Routes, ExtraOptions } from '@angular/router';
import { BasicLayout } from '../layouts';
import { TermsAndConditionsComponent } from './terms-and-conditions/terms-and-conditions.component';

const routes: Routes = [
{
path: '', component: BasicLayout,
children: [
{ path: 'terms-and-conditions', component: TermsAndConditionsComponent }
]
}
];

const routerOptions: ExtraOptions = {
useHash: false,
anchorScrolling: 'enabled',
scrollPositionRestoration: 'enabled'
};

@NgModule({
declarations: [],
imports: [
CommonModule,
RouterModule.forRoot(routes, routerOptions)
],
exports: [
RouterModule
]
})
export class TermsRoutingModule { }

我在这里错过了什么?如果有更简单的方法是什么?

PS.: 我被禁止像这样使用 JS DOM 操作:

 this.route.fragment.subscribe((fragment: string): void => {
if (fragment && document.getElementById(fragment) !== null) {
document.getElementById(fragment).scrollIntoView({ behavior: "smooth" });
}

最佳答案

文档很困惑,但您不需要使用片段(或路由器或额外选项)来使用 viewportscroller,它是完全独立的。您应该能够为要滚动到的元素分配一个 ID,只需在点击事件上使用 this.viewportscroller.scrollToAnchor(elementID) 即可。我最近使用了它,它在 ngOnInit 生命周期 Hook 中起作用。

如果您需要使用路由器来实际导航到页面的一部分,请尝试查看这篇文章以了解如何实现路由器链接 by Ben Nadel

关于当我被路由到所需位置时,Angular viewportScroller 第一次不工作#fragment,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54570988/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com