路由就是根据不同的url地址,动态的让根组件挂载其他组件来实现一个单页面应用。
安装路由
ng generate module app-routing --flat --module=app
路由安装后的变化
- 增加了app-routing.module.ts (配置路由的模块)
- 在app.module.ts中引入了AppRoutingModule的模块(注入)
- 在app.component.html中有< router-outlet >< / router-outlet >
步骤
- 1.创建项目
- 2.创建需要的组件(ng g c components/news)
- 3.找到app-routing.module.ts配置路由
引入组件
//将新建的组件引入
import { NewsComponent } from './component/news/news.component';
import { HomeComponent } from './component/home/home.component';
import { ProdComponent } from './component/prod/prod.component';
import { NewscontentComponent } from './component/newscontent/newscontent.component';
配置路由
const routes:Routes=[
{
path:'home',component:HomeComponent
},
{
path:'news',component:NewsComponent
},
{
path:'newscontent',component:NewscontentComponent
},
{
path:'prod',component:ProdComponent
}
];
- 4.找到app.component.html根组件模块,配置router-outlet显示动态加载的路由
<h1>我是根组件</h1>
<header>
<a [routerLink]="['/home']">首页</a>
<a routerLink='/news'>新闻</a>
<a [routerLink]="[ '/prod']">产品</a>
</header>
<router-outlet></router-outlet>
- 5.设置默认组件
{
path:'**',
redirectTo:'home'//任意的路由,匹配不到路由的时候加载的组件,或者跳转的路由
}
- 6.活跃时的组件(跳转是的默认样式)
<a [routerLink]="[ '/home' ]" routerLinkActive="active">home</a>
<a [routerLink]="[ '/news' ]" routerLinkActive="active">news</a>
<a [routerLink]="[ '/prod' ]" routerLinkActive="prod">home</a>
.active{
color:red
}
路由跳转传值
新闻跳转到新闻详情
创建新闻详情组件 newcontentComponent
在news.component.html中
<a [routerLink]="[ '/newscontent' ]">跳转新闻详情</a>