Angular|Angular data 3

路由
1、命令新建 router项目 加参数 --routing

ng new router --routing

Angular|Angular data 3
文章图片
image.pn Angular|Angular data 3
文章图片
image.png 实例 在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 { }

【Angular|Angular data 3】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 父模板代码
主页 商品详情

product.component.html 子组件模板之一代码
这是一个商品组件

    推荐阅读