路由
1、命令新建 router项目 加参数 --routing
ng new router --routing
实例
在app-routing.module.ts中引入Home 和Product 两个组件的路由
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import {HomeComponent} from "./home/home.component";
import {ProductComponent} from "./product/product.component";
const routes: Routes = [
{path:'',component:HomeComponent},//配置默认路由
{path:'product',component:ProductComponent},
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
配置404组件 (通配符路由设置)
完整代码
app-routing.module.ts代码
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import {HomeComponent} from "./home/home.component";
import {ProductComponent} from "./product/product.component";
import {Code404Component} from "./code404/code404.component";
const routes: Routes = [
{path:'',component:HomeComponent},
{path:'product',component:ProductComponent},
/* 路由配 通配符路由通常放最后面 */
{path:'**',component:Code404Component},
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
app.module.ts代码
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
import { ProductComponent } from './product/product.component';
import { Code404Component } from './code404/code404.component';
@NgModule({
declarations: [
AppComponent,
HomeComponent,
ProductComponent,
Code404Component
],
imports: [
BrowserModule,
AppRoutingModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
app.component.ts 代码(父组件)
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 {
/*通过构造方法拿到 router对象 */
constructor(private router: Router) {
}
toProductDetails() {
/* 通过控制器的navigate方法来路由到product组件上面 */
this.router.navigate(['/product']);
}
}
app.component.html 父模板代码
<a [routerLink]="['/']">主页</a>
<a [routerLink]="['/product']">商品详情</a>
<input type="button" value="商品详情" (click)="toProductDetails()">
<!-- / 开头的叫根路由 ./ 开头的是子路由 -->
<!-- routerLink [] 里面可以传参数 -->
<!-- (click) 括号里面的是Angular的事件绑定用法 绑定到 组件控制器中的toProductDetails方法 -->
<!-- 路由暂位符号 -->
<router-outlet></router-outlet>
product.component.html 子组件模板之一代码
<p>
这是一个商品组件
</p>