我们可以使用“ @ angular / router”中的Router和NavigationEnd,因此可以滚动到每个路线的网页顶部。
方法:
- 首先,我们需要从app.module.ts文件和app.component.ts中的“ @ angular / router”导入Router和NavigationEnd。
- 然后我们需要在构造函数创建一个实例。
- 创建实例后,我们需要在ngOninit()生命周期挂钩中使用它们。
- 在ngOninit()挂钩中,我们需要订阅路由器的事件,并检查它是否是NavigationEnd的实例。
- 然后,在检查之后,我们可以将window.scrollTo()函数与(0,0)坐标一起使用以导航到顶部。
完成上述步骤后,使用以下命令启动您的项目。
ng serve --open
下面是上述步骤的实现:
app.module.ts:
Javascript
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouterModule, Routes } from '@angular/router';
import { AppComponent } from './app.component';
const routes: Routes = [
{ path: '', component: AppComponent },
];
@NgModule({
imports: [ BrowserModule,
RouterModule.forRoot(routes) ],
declarations: [ AppComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule { }
Javascript
import { Component, OnInit } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';
@Component({
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent implements OnInit {
constructor(private router: Router) { }
ngOnInit() {
this.router.events.subscribe((event) => {
if (!(event instanceof NavigationEnd)) {
return;
}
window.scrollTo(0, 0)
});
}
}
HTML
Hello,Geek!
GeeksForGeeks is a website which
is a one stop destination for all
the computer science related
doubts.
Click on the below button
to starting learning.
Featured
Featured
app.component.ts:
Java脚本
import { Component, OnInit } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';
@Component({
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent implements OnInit {
constructor(private router: Router) { }
ngOnInit() {
this.router.events.subscribe((event) => {
if (!(event instanceof NavigationEnd)) {
return;
}
window.scrollTo(0, 0)
});
}
}
app.component.html:
的HTML
Hello,Geek!
GeeksForGeeks is a website which
is a one stop destination for all
the computer science related
doubts.
Click on the below button
to starting learning.
Featured
Featured
输出: