anchorScroll与角7.x.x静态页面?

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

我对条款和条件的静态页面。

链接都设置这样的

<li>
    <a [routerLink]=""
    fragment="user-submission-testimonials">User Submission Testimonials</a>
</li>

术语-routing.module.ts:

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 { }

什么管理长卷“动画”:

export class TermsAndConditionsComponent implements OnInit, AfterViewChecked {

  constructor(private route: ActivatedRoute, private element: ElementRef) { }

  ngOnInit() { }

  ngAfterViewChecked(): void {
    console.log(this.element.nativeElement.id)
    this.route.fragment.subscribe((fragment: string): void => {
      if (fragment && this.element.nativeElement && this.element.nativeElement.id === fragment) {
        this.element.nativeElement.scrollIntoView({ behavior: 'smooth' });
      }
    });
  }
}

我已经CONSOLE.LOG为了调试的目的,它打印出什么甚至没有定义。这只是空白。但是,如果我尝试定期JS像这样做:

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

你不准我用JS,它需要与TS完成。或者至少,我的上司说,这是不是TS,我需要用角相关TS做

我见过一个帖子directive solution on reddit because of ElementRef XSS isues但它不是为我工作:(我在想什么?

angular typescript angular2-directives anchor-scroll
1个回答
0
投票

使用ViewportScroller

ViewportScroller是,你可以在构造函数中注入服务。它提供不同势类型的方法,使用scrollToAnchor方法来实现基于ID锚滚动。

尝试这个:

component.html

<li>
    <a [routerLink]=""
    fragment="'user-submission-testimonials'">User Submission Testimonials</a>
</li>

component.ts

import { Location, ViewportScroller } from '@angular/common';
import { Router, Scroll, NavigationEnd } from '@angular/router';


export class TermsAndConditionsComponent implements OnInit {

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

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

}}

参考:https://blog.ninja-squad.com/2018/07/26/what-is-new-angular-6.1/

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