Angular 2 - 从父组件的`first child`组件到'second child`组件的路由

时间:2016-04-27 10:23:59

标签: javascript routing angular

我正在尝试从子组件到父组件的另一个子组件进行简单的路由。 router-outlet在父组件中定义。以下是我试图实现这一目标的方法:

parent.ts

import {Component} from 'angular2/core';
import {RouteConfig,ROUTER_PROVIDERS,ROUTER_DIRECTIVES} from 'angular2/router';
import {bootstrap} from 'angular2/platform/browser';
import {FirstChildCmp} from "./first_child";
import {SecondChildCmp} from "./second_child";

@Component({
  selector: 'app',
  template: `
  <router-outlet></router-outlet>
  `,
  directives: [ROUTER_DIRECTIVES]
})
@RouteConfig([
  {path: '/first_child', component: FirstChildCmp, name: 'FirstChild', useAsDefault:true},
  {path: '/second_child',component: SecondChildCmp, name:'SecondChild'}
])
export class ParentCmp{}

bootstrap(ParentCmp,[
  ROUTER_PROVIDERS
]);

first_child.ts

import {Component} from 'angular2/core';
import {ROUTER_DIRECTIVES} from 'angular2/router';

@Component({
  selector: 'child',
  template: `
  <a [routerLink]="[SecondChild]">Go to second child</a>
  `,
  directives: [ROUTER_DIRECTIVES]
})
export class FirstChildCmp{}

second_child.ts

import {Component} from 'angular2/core';

@Component({
  selector: 'child',
  template: `
  This is second child.
  `
})
export class SecondChildCmp{}

当用户点击Go to second child时,我想显示第二个子组件的模板。但我收到以下错误:

  

组件&#34; FirstChildCmp&#34;没有路由配置。

但我不想在FirstChildCmp中定义配置,而是想使用父配置。我在plunker here

上重新制作了这个问题

1 个答案:

答案 0 :(得分:3)

FirstChild.ts Plnkr

@Component({
  selector: 'child',
  template: `
  <a [routerLink]="['SecondChild']">Go to second child</a>
  `,
  directives: [ROUTER_DIRECTIVES]
})
export class FirstChildCmp{}

['SecondChild']你错过了引号。它必须是一个字符串。