anchorScroll на статической странице с Angular 7.xx?
У меня есть статическая страница для условий.
Ссылки настроены так
<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
Я видел решение почтовой директивы на reddit из-за проблем ElementRef XSS, но у меня это не работает:(Что мне не хватает?
1 ответ
Используйте ViewportScroller
ViewportScroller - это сервис, который вы можете добавить в конструктор. Он предоставляет различные типы методов. Используйте метод scrollToAnchor для достижения прокрутки привязки на основе идентификатора.
Попробуй это:
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/