Angular7.2.7路由使用 Angular7.2.7路由使用初体验
默默无闻 人气:0本文记录自己在学习angular中对路由的理解
angular路由不在angular的包中, 如果要使用angular的路由, 需要从@angular/router中引入
路由的使用:
子路由使用:
import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; const route: Routes = [ {path: 'browse-product', component: BrowseProductComponent}, {path: 'buy-product', component: BuyProductComponent} ] @NgModule({ imports: [RouterModule.ferChild(route)], // 子路由使用ferChild方法 exports: [RouterModule] }) export class ChildRoutingModule {}
父组件中:
import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; const route: Route = [ { path: '', children: [ {path: '', redirectTo: '/user/browse-product', pathMatch: 'full'}, {path: 'user', loadChildren: './user/user.module#UserModule'}, {path: 'admin', loadChildren: './admin/admin.module#AdminModule'}, ] } ] @NgModule({ imports: [RouterModule.forRoot(root, {useHash: false})], exports: [RouterModule] }) export class ParentRoutingModule {}
在app.module.ts中导入模块
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { RouterModule } from '@angular/router'; import { ParentRoutingModule } from 'parentRoutingModule'; @NgModule({ declarations: [ AppComponent, ], imports: [ BrowserModule, RouterModule, ParentRoutingModule ] })
然后在app.component.html中加入router-outlet即可, router-outlet就是路由的出口, 表示路由对应的组件应该在这里显示.
<h1>Angular Router</h1> <nav> <a routerLink="/user/browse-product">browse-product</a> <a routerLink="/user/buy-product">buy-product</a> <a routerLink="/admin/manage-product">manage-product</a> <a routerLink="/admin/operator-record">operator-record</a> </nav> <router-outlet></router-outlet>
加载全部内容