路由就是根据不同的url地址,动态让根组件挂载其他组件来实现一个单页面应用
1.把app.modeule.ts文件中创建组件时自动引入的组件复制到app-routing.module.ts中
如下:
app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { RouteComponent01Component } from './conponent/route-component01/route-component01.component';
import { RouteComponent02Component } from './conponent/route-component02/route-component02.component';
@NgModule({
declarations: [
AppComponent,
HomeComponent,
HeaderComponent,
FooterComponent,
NewsComponent,
RouteComponent01Component,
RouteComponent02Component
],
imports: [
BrowserModule,
AppRoutingModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
app-routing.module.ts
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { RouteComponent01Component } from './conponent/route-component01/route-component01.component';
import { RouteComponent02Component } from './conponent/route-component02/route-component02.component';
const routes: Routes = [
{path:'rc1',component:RouteComponent01Component},
{path:'rc2',component:RouteComponent02Component},
//匹配不到路由的时候加载的组件 或跳转的路由
{path:'**',redirectTo:'rc1'}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
2.然后可直接访问路径
3.跳转路由
app.component.css: .header{ height: 40px; line-height: 40px; background-color: #000; color: #fff; } a{ color: #ffffff; padding: 10px 40px; } app.component.html: <header class="header"> <a [routerLink]="['/rc1']">rc1(这是动态改变地址)</a> <a routerLink='/rc2'>rc2(这是静态地址)</a> </header>
4.路由选中
app.component.css: .active{ color: red; }
app.component.html: <header class="header"> <a [routerLink]="['/rc1']" routerLinkActive="active">rc1(这是动态改变地址)</a> <a routerLink='/rc2' routerLinkActive="active">rc2(这是静态地址)</a> </header>