当前位置:主页 > 网页前端 > AngularJS >

Angular7.2.7路由使用初体验

时间:2021-06-27 08:19:58 | 栏目:AngularJS | 点击:

本文记录自己在学习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> &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>

您可能感兴趣的文章:

相关文章