我有父组件,它定义了一个路由器,它指向2个子组件,每个组件本身都有一个路由器,类似
父
import { Component } from '@angular/core';
import { RouteConfig, ROUTER_DIRECTIVES, Router } from '@angular/router-deprecated';
import {Child1WithRouterComponent} from './childWithRouter1.component';
import {Child2WithRouterComponent} from './childWithRouter2.component';
@Component({
selector: 'mex-app',
template: `
<h2>MEAN2 Examples</h2>
<div style="width: 30%;float:left">
<button type="button" style="width: 100%"
(click)="child1()">Child 1</button>
<button type="button" style="width: 100%"
(click)="child2()">Child 2</button>
</div>
<div style="width: 70%;float:left">
<router-outlet></router-outlet>
</div>
`,
directives: [ROUTER_DIRECTIVES]
})
@RouteConfig([
{path: '/child1/...', name: 'Child1', component: Child1WithRouterComponent, useAsDefault: true},
{path: '/child2/...', name: 'Child2', component: Child2WithRouterComponent}
])
export class AppComponent {
constructor(private router: Router) {}
child1() {
this.router.navigate['Child1']
}
child2() {
this.router.navigate['Child2']
}
}
Child1
import { Component } from '@angular/core';
import { RouteConfig, ROUTER_DIRECTIVES, Router } from '@angular/router-deprecated';
import {GrandChild1Component} from './grandChild1.component';
import {GrandChild2Component} from './grandChild2.component';
@Component({
selector: 'mex-child1',
template: `
<h3>Child with router</h3>
<button type="button"
(click)="goToGrandChild1()">GO TO GRAND CHILD1</button>
<button type="button"
(click)="goToGrandChild2()">GO TO GRAND CHILD2</button>
<router-outlet></router-outlet>
`,
directives: [ROUTER_DIRECTIVES],
})
@RouteConfig([
{path: '/grand-child-1', name: 'GrandChild1', component: GrandChild1Component},
{path: '/grand-child-2', name: 'GrandChild2', component: GrandChild2Component}
])
export class Child1WithRouterComponent {
constructor(private router: Router) {}
goToGrandChild1() {
this.router.navigate(['GrandChild1'])
}
goToGrandChild2() {
this.router.navigate(['GrandChild2'])
}
}
Child2 与 Child1 相同,只是它的RouteConfig
@RouteConfig([
{path: '/grand-child-3', name: 'GrandChild3', component: GrandChild3Component},
{path: '/grand-child-4', name: 'GrandChild4', component: GrandChild4Component}
])
父级应该能够以编程方式从Child1导航到Child2,反之则执行this.router.navigate['Child1']
或this.router.navigate['Child2']
。
不幸的是,当我尝试从Child1(默认)导航到Child2时,没有任何事情发生。
提前感谢您的支持
答案 0 :(得分:0)
当您导航到['ChildX']时,我认为需要一个默认的子孙,或者您在传递的参数中指定一个以进行导航,如
_this.router.navigate(['Child1', 'GrandChild1'])