我有一个关于条款和条件的静态页面。
链接设置如下
<li>
<a [routerLink]=""
fragment="user-submission-testimonials">User Submission Testimonials</a>
</li>
terms-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
我看过一条帖子directive solution on reddit because of ElementRef XSS isues 但是它对我不起作用:( 我想念什么?
答案 0 :(得分:0)
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/