您可以这样使用Angular2 组件路由器:
(注意:为了简单起见,我没有添加输入元素,而是使用a
了元素。同样的过程也适用,调用一个函数来告诉路由器将加载的组件插入到<router-outlet>
.
app.component.ts
import { Component } from '@angular/core';
import { Router } from '@angular/router';
@Component({
selector: 'my-app',
template: `
<div>
<!-- to show how the function can be called -->
<a href="#" (click)="load('/page1')">Page 1</a>
<!-- Right way with links -->
<a href="#" routerLink="/page1">Page 1</a>
<router-outlet></router-outlet>
</div>
`
})
export class AppComponent {
constructor(private router: Router)
load(path: string): void {
this.router.navigate([path]);
}
}
app.routing.ts
import { ModuleWithProviders } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
const appRoutes: Routes = [
{
path: "page1",
component: "PageOneComponent"
}
];
export const appRoutingProviders: any[] = [
];
export const appRouting: ModuleWithProviders = RouterModule.forRoot(appRoutes);
app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { appRouting, appRoutingProviders } from './app.routing';
@NgModule({
imports: [
BrowserModule,
FormsModule,
appRouting,
],
declarations: [
RootComponent,
],
providers: [
appRoutingProviders
],
bootstrap: [AppComponent]
})
export class AppModule { }
干杯!