1.通过超链接导航
使用一下命令新建一个项目:
ng new router --routing // 不加-routing参数,可以在app.module.ts配置路由
生成项目时添加了–routing参数后,会多生成一个app-routing.module.ts文件:
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
const routes: Routes = [
{
path:'',
children: []
}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule],
providers:[]
})
export class AppRoutingModule { }
在app.module.ts中也会多引入AppRoutingModule:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import {FormsModule} from '@angular/forms';
import {HttpModule} from '@angular/http';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
FormsModule,
HttpModule,
AppRoutingModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
在app.component.html中会加入router-outlet
<h1>
{{title}}
</h1>
<router-outlet></router-outlet>
新生成两个组件ng g component home,ng g component product
然后修改app-routing.modules.ts,为了保证通用性,这里写地址的时候不要在前面加上/
const routes: Routes = [
{path:'',component:HomeComponent},
{path:'product',component:ProductComponent}
];
修改app.component.html
<a [routerLink]="['/']">主页</a>
<a [routerLink]="['/product']">商品详情</a>
<router-outlet></router-outlet>
此时,当你访问localhost:4200的时候显示的是home works!,当你点击商品详情,会显示product works!并且地址变成了localhost:4200/product
2.通过触发事件导航
修改app.component.html和app.component.ts
<a [routerLink]="['/']">主页</a>
<a [routerLink]="['/product']">商品详情</a>
<input type="button" value="商品详情" (click)="toProductDetails()">
<router-outlet></router-outlet>
import { Component } from '@angular/core';
import {Router} from "@angular/router";
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app';
constructor(private router: Router){}
toProductDetails(){
this.router.navigate(['/product']);
}
}
运行程序,点击按钮,下边就会显示product works!
3.配置404页面路由
新生成一个组件ng g component code404
修改app-routing.module.ts
const routes: Routes = [
{path:'',component:HomeComponent},
{path:'product',component:ProductComponent},
{path:'**',component:Code404Component}
];
当访问一个不存在的路径时会显示code404 works!
显示路由是从上往下匹配地址,如果把{path:’**’,component:Code404Component}放到前面不管访问那个页面都会显示code404了。所以具有通用性的路由要放到最后边。