我可以在Angular中有两个或更多<router-outlet>吗?

时间:2018-01-22 13:01:21

标签: angular routing router

我希望在我的Angular应用中有两个<router-outlet>,例如下面的方案。有可能吗?

enter image description here

1 个答案:

答案 0 :(得分:0)

在版本2或更高版本中,要在同一模板中使用多个路由器插座,您需要在RouterModule.forRoot结构中指定children元素。

<强> app.component.ts

    import { BrowserModule } from '@angular/platform-browser';
    import { BrowserModule } from '@angular/platform-browser';
    import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
    import { NgModule } from '@angular/core';
    import { CommonModule } from '@angular/common';
    import { FormsModule, ReactiveFormsModule } from '@angular/forms';
    import { HttpModule } from '@angular/http';
    import { RouterModule } from '@angular/router';
    import { AnotherPageComponent } from './anotherpage.component';
    import { AnotherPageSubComponent1 } from './anotherpagesubcomponent1.component';
    import { AnotherPageSubComponent2 } from './anotherpagesubcomponent2.component';

@Component({ 
    template: `
    <h1>Angular Router</h1>
    <nav> <a routerLink="/home" routerLinkActive="active"> Home </a>
          <a routerLink="/anotherpage" routerLinkActive="active"> Another page </a>
          <a routerLink="/about" routerLinkActive="active"> About </a>
    </nav>
    <router-outlet></router-outlet> `
})

export class AppComponent {}
@NgModule({
    imports: [
        CommonModule,
        HttpModule,
        FormsModule,
        ReactiveFormsModule,
        RouterModule.forRoot([
            { path: "", component: HomeComponent, data: { title: "Home" } },
            { path: "home", component: HomeComponent, },
            { path: "anotherpage", component: AnotherPageComponent,
                children:
                [ 
                    { path: "", redirectTo: "anotherpagesubcomponent1", pathMatch: "full" },
                    { path: "anotherpagesubcomponent1", component: AnotherPageSubComponent1,
                    { path: "anotherpagesubcomponent2", component: AnotherPageSubComponent2
                ]
            },
            { path: "about", component: AboutComponent,
        ])
    ],
    exports: [ RouterModule ]})

anotherpage.component.ts (是您的第1页)

@Component({
    template: `
    <h2>Angular Router on Another Page</h2>
    <nav>
        <a routerLink="/anotherpagesubcomponent1" routerLinkActive="active"> Another page sub component 1</a>
        <a routerLink="/anotherpagesubcomponent2" routerLinkActive="active"> Another page sub component 2</a>
    </nav>
    <router-outlet></router-outlet>
    `
})

export class AnotherPageComponent {}

如果清楚的话,请告诉我。