1、 app.module.ts
import {BrowserModule} from '@angular/platform-browser';
import {NgModule} from '@angular/core';
import {FormsModule} from '@angular/forms';
import {HttpModule} from '@angular/http';
import {RouterModule, Routes} from "@angular/router";
import {AppComponent} from './components/app.component';
import {HomeComponent} from "./components/home.component";
import {ContactComponent} from "./components/contact.component";
// 这样就实现了延时加载
// 我们使用属性loadChildren而不是component 。
// 我们传递一个字符串而不是一个符号,以避免加载模块。
// 我们不仅定义了模块的路径,还定义了类的名称。
const MyRouter:Routes = [
{
path: "home",
component: HomeComponent
},
{
path: "about",
loadChildren: "app/about.module#AboutModule"
},
{
path: "contact",
component: ContactComponent
},
{
path: "**",
redirectTo: "home"
}
];
@NgModule({
declarations: [
AppComponent,
HomeComponent,
ContactComponent
],
imports: [
BrowserModule,
FormsModule,
HttpModule,
RouterModule.forRoot(MyRouter)
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule {
}
2、app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: '../templates/app.component.html'
})
export class AppComponent {
}
3、app.component.html
<a [routerLink]="['home']" routerLinkActive="active">首页</a>
<a [routerLink]="['contact']" routerLinkActive="active">联系我们</a>
<a [routerLink]="['about']" routerLinkActive="active">关于我们</a>
<a [routerLink]="['about/list']" routerLinkActive="active">我们列表</a>
<router-outlet></router-outlet>
4、home.component.ts
import {Component} from "@angular/core";
@Component({
selector: "my-home",
template: "首页"
})
export class HomeComponent {
constructor() {
console.log("home");
}
}
5、about.module.ts
import {NgModule} from '@angular/core';
import {RouterModule, Routes} from "@angular/router";
import {AboutComponent} from "./components/about.component";
import {ListComponent} from "./components/list.component";
const childRouter:Routes = [
{
path: '',
component: AboutComponent
},
{
path: "list",
component: ListComponent
}
];
@NgModule({
imports: [
RouterModule.forChild(childRouter)
],
declarations: [
AboutComponent,
ListComponent
]
})
export class AboutModule {
}
6、about.component.ts
import {Component, OnInit} from "@angular/core";
@Component({
selector: "my-about",
template: "关于我们"
})
export class AboutComponent {
constructor() {
console.log("about");
}
}
7、list.component.ts
import {Component} from "@angular/core";
@Component({
selector: "my-list",
template: "列表"
})
export class ListComponent {
constructor() {
console.log("list");
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。