Angular 路由简介

ANGLE 2+中的路由器使您可以轻松地为您的应用定义路由。以下是在你的应用程序中开始使用基本路线的步骤:

1.基本标签

如果您使用ANGLE CLI创建项目,则默认情况下会在index.html中添加一个基本标记,但如果您不使用ANGLE CLI,则需要自己添加它。您所要做的就是在文档头中的任何样式或脚本声明之前添加以下内容:

1<base href="/">

2.模块配置

接下来,您将在app模块 (app.mode.ts)中导入RouterModule和Routers,并定义一个包含您的路由配置的数组。在主应用程序模块中导入的RouterModule使路由器在您的应用程序中随处可用。还请记住,当您的应用程序增长时,您可能希望在单独的路由模块中定义路由配置,以更好地分离关注点:

 1import { BrowserModule } from '@angular/platform-browser';
 2import { NgModule } from '@angular/core';
 3import { FormsModule } from '@angular/forms';
 4import { HttpModule } from '@angular/http';
 5import { RouterModule, Routes }   from '@angular/router';
 6
 7import { AppComponent } from './app.component';
 8import { ProfileComponent } from './profile/profile.component';
 9import { SettingsComponent } from './settings/settings.component';
10import { HomeComponent } from './home/home.component';
11const routes: Routes = [
12  { path: '', component: HomeComponent },
13  { path: 'profile', component: ProfileComponent },
14  { path: 'settings', component: SettingsComponent }
15];

3.&routerLink模板

应用程序组件成为您的应用程序的外壳,并在应该呈现路由的位置接受标记。锚标记使用routerLink绑定而不是href属性来指向特定的路由。下面是您的app.Component.ts应该是什么样子。

另请注意,使用了routerLinkActive绑定,它会将给定的类名添加到当前活动的路由中,从而可以轻松地使用一些CSS设置活动链接的样式:

1<nav>
2  <a routerLink="/"
3     routerLinkActive="active">Home</a>
4  <a routerLink="/profile"
5     routerLinkActive="active">Profile</a>
6  <a routerLink="/settings"
7     routerLinkActive="active">Settings</a>
8</nav>
Published At
Categories with 技术
Tagged with
comments powered by Disqus