1 生成带路由的项目
ng new demo --routing
2 创建组件
ng g component zujian/home
ng g component zujian/news
ng g component zujian/newscontent
3 在路由文件app-routing.module.ts里引入组件,写路由规则
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import {HomeComponent} from './zujian/home/home.component';
import {NewsComponent} from './zujian/news/news.component';
import {NewscontentComponent} from './zujian/newscontent/newscontent.component';
const routes: Routes = [
{path: 'home', component: HomeComponent},
{path: 'news', component: NewsComponent},
{path: 'newscontent/:id', component: NewscontentComponent},
{
path: '**',/*匹配不到的任意的路由*/
redirectTo: '/home',
pathMatch: 'full'
}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
4 app.component.html
<h1>
<a routerLink='/home' routerLinkActive="active">home</a>
<br>
<a routerLink='/news' routerLinkActive="active">news</a>
</h1>
<router-outlet></router-outlet>
routerLinkActive用来设置选中路由的状态
app.component.css
.active{
color:red;
}