Angular7.2.7路由使用初体验

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> &nbsp; <a routerLink="/user/buy-product">buy-product</a>&nbsp; <a routerLink="/admin/manage-product">manage-product</a>&nbsp; <a routerLink="/admin/operator-record">operator-record</a>&nbsp; </nav> <router-outlet></router-outlet>

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/1a75cf876aa0e640565f207f8868d6b5.html