为了避免出现这种混淆,可以在路由模块中添加以下代码,明确指定要使用的路由策略:
// app-routing.module.ts
@NgModule({
imports: [
RouterModule.forRoot([
{ path: '', component: HomeComponent },
{ path: 'about', component: AboutComponent },
{ path: '**', component: PageNotFoundComponent }
], {scrollPositionRestoration: 'enabled'}) // 显式设置锚点滚动
],
exports: [RouterModule]
})
export class AppRoutingModule { }
在这个例子中,我们为根路由添加了一个 scrollPositionRestoration
配置项,它将确保在导航到新页面时自动滚动到锚点位置。此外,我们还为通配符路由“**”指定了一个默认的 PageNotFoundComponent
。
这样配置路由模块之后,就能够在不会出现锚点滚动和通配符路由“**”之间的混淆了。