(四)、Angular4.0 路由基础

时间:2021-05-24 18:34:03

一、新建一个angular路由项目 router

ng new router --routing

二、生成三个组件

ng g component home
ng g component product
ng g component code404

三、home.component.html

<p>
  这里是主页组件
</p>

四、product.component.html

<p>
  这里是商品信息组件
</p>

五、code404.component.html

<p>
  页面不存在
</p>

六、app.component.html

<a [routerLink]="['/']">主页</a>
<a [routerLink]="['/product']">商品详情页</a>
<input type="button" value="商品详情" (click)="toProductDetails()"/>
<router-outlet></router-outlet>

七、配置路由 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],
  providers: []
})
export class AppRoutingModule { }

八、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 {
  title = 'app works!';

  constructor(private router: Router) {

  }

  toProductDetails() {
    this.router.navigate(['/product']);
  }

}

九、npm run start 启动项目,测试两个连接一个按钮和错误的url地址