简体   繁体   中英

Angular2 Routing - Child template not dispalying

I am trying to learn angular 2 routing and I am stuck here I can't get the template of child component to display. I have the following two pages

page1.ts

import {Component} from 'angular2/core';

@Component({
    selector: "page1",
    template: `page 1 goes here.`
})
export class Page1Cmp{}

page2.ts

import {Component} from 'angular2/core';
import {RouterLink,RouteConfig} from 'angular2/router';
import {ChildCmp} from './child';

@Component({
    selector: "page2",
    template: `Hello its page 2
    <router-outlet></router-outlet>`
})
@RouteConfig([
    {path: "/", component: ChildCmp, name: "Child", useAsDefault: true}
  ])
export class Page2Cmp{}

Here is the child component that page2.ts is trying to route

child.ts

import {Component} from 'angular2/core';

@Component({
    selector: "child",
    template: `child content goes here.`
})
export class ChildCmp{}

This child component is not being displayed on page2 Here is the root component

app.ts

import {Component} from "angular2/core";
import {bootstrap} from "angular2/platform/browser";
import {ROUTER_DIRECTIVES, RouteConfig, ROUTER_PROVIDERS} from "angular2/router";
import {Page1Cmp} from './page1';
import {Page2Cmp} from './page2';

@Component({
    selector: "app",
    template: `<a [routerLink]="['Page1']">Page1</a> | <a [routerLink]="['Page2']">Page2</a>
    <router-outlet></router-outlet>
    `,
    directives: [ROUTER_DIRECTIVES]
})
@RouteConfig([
    {path: "/page1", name: "Page1", component: Page1Cmp, useAsDefault: true},
    {path: "/page2/...", name: "Page2", component: Page2Cmp}
])
class MyApp{}

bootstrap(MyApp, [
    ROUTER_PROVIDERS
]);

When I route to page2 I don't see the template of child.ts component. I re-produced the problem on plunker here

plunker

import {RouterLink,RouteConfig,ROUTER_DIRECTIVES} from 'angular2/router'; 

@Component({
    selector: "page2",

    directives: [ROUTER_DIRECTIVES],
    //add this and it will start working as expected.

    template: `<br>Hello its page 2<br>
    <router-outlet></router-outlet>`
})

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