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

问题描述 投票:2回答:1

标题中的viewportScroller出现问题。

在我的项目中,我需要从嵌套的URL重定向到一个简单的静态条款和条件网站(该网站具有导航边栏,可在网站内导航到每个锚点。]]

哪个工作正常,但一开始并没有滚动到所需的片段。如果您访问上述条款和条件网站,然后再次执行整个工作流程(转到嵌套的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出现问题。在我的项目中,我需要从嵌套的URL重定向到一个简单的静态条款和条件网站(该网站的导航侧栏为...

angular typescript angular2-routing
1个回答
0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.