要在Angular中将组件与URL映射到路由中,需要使用Angular的路由模块。下面是一个使用Angular路由模块将组件与URL映射的示例:
app.module.ts
)中导入RouterModule
和Routes
:import { RouterModule, Routes } from '@angular/router';
@NgModule
装饰器中配置路由:@NgModule({
imports: [
RouterModule.forRoot([
{ path: 'home', component: HomeComponent },
{ path: 'about', component: AboutComponent },
{ path: 'contact', component: ContactComponent }
])
],
exports: [RouterModule]
})
export class AppModule { }
在上面的代码中,我们配置了三个路由路径:home
、about
和contact
,并将它们与相应的组件(HomeComponent
、AboutComponent
和ContactComponent
)进行了映射。
app.component.ts
)中添加
来显示路由组件:
routerLink
指令来生成链接并导航到相应的URL:
以上代码将在导航栏中创建三个链接,分别指向/home
、/about
和/contact
。
这样,当用户点击导航栏中的链接时,Angular会根据路由配置加载相应的组件并显示在
中。
希望以上示例可以帮助您理解如何在Angular中将组件与URL在路由中进行映射。