【发布时间】:2018-03-21 09:01:10
【问题描述】:
我想要实现的是单击并平滑滚动到底部/指定的 div 区域,我用标签定义,就像我认为它应该是这样的。
这是为 JQuery 编写的 w3school 示例中的实时示例:https://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_eff_animate_smoothscroll
我所做的就是从这个答案中窥视:Angular2 Routing with Hashtag to page anchor
但我不太明白答案,答案看起来像这样:
这部分是HTML部分:
<a [routerLink]="['somepath']" fragment="Test">Jump to 'Test' anchor </a>
在下面,router.navigate 是我应该把代码放在哪里? component.ts 对吗?但是我如何访问这个功能?我应该实现(点击)吗?
this._router.navigate( ['/somepath', id ], {fragment: 'test'});
在这下面,我明白了,它应该写在我的 component.ts 中:
** Add Below code to your component to scroll**
import {ActivatedRoute} from '@angular/router'; // <-- do not forget to import
private fragment: string;
constructor(private route: ActivatedRoute { }
ngOnInit() {
this.route.fragment.subscribe(fragment => { this.fragment = fragment; });
}
ngAfterViewInit(): void {
try {
document.querySelector('#' + this.fragment).scrollIntoView();
} catch (e) { }
}
“somepath”是什么意思?我应该在我的 routes.ts 中添加一条路线,对吗?通常,我在这里添加一个新路径,例如:
export const routes: Routes = [
{ path: '', redirectTo: '/home', pathMatch: 'full' },
{ path: 'product', redirectTo: '/product' },
...homeRoutes,
...productRoutes
];
谁能提供完整的 HTML、路由和组件示例代码?
【问题讨论】:
-
从我阅读和搜索的内容来看,这将是一个 SMOOTH SCROLL 的代码,它不像我认为的 JQuery,所以我决定使用这个完美工作的插件: npmjs.com/package/@nicky-lenaers/ngx-scroll-to随意使用
标签: angular typescript scroll routes