简体   繁体   中英

Angular 2 Routing in more then one component

I have an app component where the routes are defined and the <router-outlet></router-outlet> is set. I also have a menu component where I would like to set the [routerLink] using the app routes. How do I link bought of them together (Share routes). App Component:

import {Component, View} from 'angular2/core';
import {ROUTER_PROVIDERS,RouteConfig} from 'angular2/router';
import {bootstrap} from 'angular2/platform/browser';
import {HomeComponent} from './../../components/home/home';
@Component({
    selector: 'app',
    moduleId: module.id,
    providers: [
        ROUTER_PROVIDERS
    ]
})
@View({
        templateUrl: 'app.html',
        styleUrls: ['app.css']
})

@RouteConfig([
    { path: '/home', name: 'Home', component: HomeComponent, useAsDefault: true }
])
class AppComponent {

}
bootstrap(AppComponent);

Menu Component:

import {Component, View} from 'angular2/core';
import {bootstrap} from 'angular2/platform/browser';


@Component({
    selector: 'left-side-column',
    moduleId: module.id,
})
@View({
    templateUrl: 'left-side-column.html',
    styleUrls: ['left-side-column.css']
})

class LeftSideColumnComponent {

}
bootstrap(LeftSideColumnComponent);

When you use the bootstrap function twice, you create several independent applications.

If you want that your menu uses routes defined in the AppComponent, you need to use the corresponding component into the app one and bootstrapping it.

Something like:

import { MenuComponent } from '...';

@Component({
  (...)
  template: `
    <left-menu></left-menu>
    <router-outlet></router-outlet>
  ` ,
  directives: [ ROUTER_DIRECTIVES, MenuComponent ]
})
export class AppComponent {
}

bootstrap(AppComponent, [ ROUTER_PROVIDERS ]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM