本节我们学习路由知识点,假如我们有三个自定义组件,分别是【首页|home】,【设置|set】和【更多|more】,需要动态挂载在根组件【app.component.html】中,当浏览器url地址输入对应组件名称,动态显示该组件对应的内容,这就是动态路由;
- 使用 CLI 创建一个项目并配置默认路由:
ng new demo01 --routing
在新建的项目【demo01】的根组件上面就会多一个ts文件【app-routing.module.ts】
此时在【app.module.ts】文件中就会新增如下信息:
import { AppRoutingModule } from './app-routing.module';
//同时在imports中声明
imports: [ //此处是模块声明
BrowserModule,
FormsModule,
AppRoutingModule, /* Routing */
HttpClientModule /* HttpClient */
],
同时在根组件的【app.component.html】文件中默认添加如下信息:
<router-outlet></router-outlet>
- 创建组件【home,set,more】
ng generate component components/home
ng generate component components/set
ng generate component components/more
路由基本配置
- 在【app-routing.module.ts】文件中配置组件路由信息:
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
//引入(需要的)自定义组件
import { HomeComponent } from './components/home/home.component';
import { SetComponent } from './components/set/set.component';
import { MoreComponent } from './components/more/more.component';
/* 【路由配置信息】 */
/* 路由配置使用符号“**”匹配时,注意顺序,路由匹配到信息不会再往后匹配 */
const routes: Routes = [
// {path:'', pathMatch:'full', redirectTo:'home'}, /* 当为''的时候,从下面定义的路由中寻找,重定向到指定的组件home */
// {path:'', component: HomeComponent}, /* 当为''的时候,重定向到指定的组件home */
{path:'home',component: HomeComponent},
{path:'set',component: SetComponent},
{path:'more',component: MoreComponent},
{path:'**', redirectTo:'home'} /* [**]任意路由,匹配不到路由的时候加载组件或者跳转(重定向)的路由 */
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
以上配置就实现路由链接的基本配置;
默认选中路由
- 在根组件【app.component.html】文件中编写基本标签:
<p>我是根组件</p>
<figure>
<p>默认选中路由</p>
<h3>
<a title="原生默认" href="http://www.jd.com" target="_blank">我们去京东</a>
<a title="blank打开" target="_blank" routerLink="/home" routerLinkActive="active">首页</a>
<a title="self打开" target="_self" routerLink="/set" routerLinkActive="active">设置</a>
<a title="top打开" target="_top" routerLink="/more" routerLinkActive="active">更多</a>
<!-- 【等效代码】 -->
<a [routerLink]="['/home']" routerLinkActive="active">首页</a>
<a [routerLink]="['/set']" routerLinkActive="active">设置</a>
<a [routerLink]="['/more']" routerLinkActive="active">更多</a>
</h3>
</figure>
<hr/>
<router-outlet></router-outlet>
为了区分在每个组件中都标记个信息,同时在根组件的html页面中添加个横线分隔区分,当选择首页的时候,下面就显示首页的信息,同时为路由激活状态(此处未编写对应的css样式),运行效果如下:
以上就是对ng 路由的基本配置介绍,下一篇我们继续介绍【路由传参】。