0

我有一个条款和条件的静态页面。

链接是这样设置的

<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,我需要用 Angular 相关的 TS 来做

由于 ElementRef XSS 问题,我在 reddit 上看到了一个发布指令解决方案, 但它对我不起作用:(我错过了什么?

4

1 回答 1

2

使用ViewportScroller

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

尝试这个:

组件.html

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

组件.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/

于 2019-02-06T13:59:09.460 回答