13-angular中的路由

时间:2020-05-25
本文章向大家介绍13-angular中的路由,主要包括13-angular中的路由使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

 路由就是根据不同的url地址,动态的让根组件挂载其他组件来实现一个单页面应用

一、Angular 创建一个默认带路由的项目

1. 命令创建项目

ng new angularRoute --skip-install

2. 创建需要的组件

ng g component components/news

ng g component components/home

ng g component components/product

3. 找到 app-routing.module.ts 配置路由

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

import { NewsComponent } from './components/news/news.component';
import { HomeComponent } from './components/home/home.component';
import { ProductComponent } from './components/product/product.component';



const routes: Routes = [
{
path:'home',component:HomeComponent

},
{
  path:'news',component:NewsComponent
  
  },
  {
    path:'product',component:ProductComponent
    
    },


];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

路由配置成功

 4. 找到 app.component.html 根组件模板 ,配置 router-outlet 显示动态加载的路由

<h1>
<a routerLink="/home">首页</a>
<a routerLink="/news">新闻</a>
</h1>
<router-outlet></router-outlet>

二 、Angular routerLink 跳转页面 默认路由

找到 app-routing.module.ts 配置默认路由

//匹配不到路由的时候加载的组件 或者跳转的路由
{
path: '**', /*任意的路由*/
// component:HomeComponent
redirectTo:'home'
}

三、Angular routerLinkActive 设 置routerLink 默认选中路由

根.html

<h1>
<a routerLink="/home" routerLinkActive="active">首页</a>
<a routerLink="/news" routerLinkActive="active">新闻</a>
</h1>

.active{
color:red;
}

四 、动态路由

原文地址:https://www.cnblogs.com/foremostxl/p/12958064.html