你可以使用@ViewChild()或类似的路由器插座吗?如果是这样的话?

Met*_*ian 12 angular2-routing angular2-services angular

我反复遇到一种情况,我想访问路由器插座另一侧存在的子组件而不是选择器:

Like:
<router-outlet></router-outlet>

NOT:
<selector-name></selector-name>
Run Code Online (Sandbox Code Playgroud)

这与我所知道的ViewChild功能相冲突,但似乎我的组件应该能够看到路由器内部的内容并与之交互,就像选择器标签内的内容一样容易.

比如我试过这个:

export class RequestItemCatsComp {
    @ViewChild('child') child: RequestItemsComp;
    ***etc...***
ngAfterViewInit() {
    if (this.child) // Always child is undefined
        this.groupId = this.child.groupId;
    }
}
Run Code Online (Sandbox Code Playgroud)

但很自然,孩子是不确定的,因为这是错误的方式.有正确的方法吗?

我正在尝试使用服务来共享数据,但后来遇到另一个问题"表达在检查后已经改变",我希望能够在没有黑客攻击或启用prod模式的情况下解决这个问题.

Mad*_*jan 33

您可以点击激活事件以获取路由器插座内实例化组件的参考.

摘自RouterOutlet文档

路由器插座将在实例化新组件时发出激活事件,并在销毁时发出激活事件.

 @Component({
  selector: 'my-app',
  template: `<h3 class="title">Basic Angular 2</h3>
  <router-outlet (activate)="onActivate($event)" ></router-outlet>
  `
})
export class AppComponent {
  constructor(){}

  onActivate(componentRef){
    componentRef.sayhello();
  }
}

@Component({
  selector: 'my-app',
  template: `<h3 class="title">Dashboard</h3>
  `
})
export class DashboardComponent {
  constructor(){}

  sayhello(){
    console.log('hello!!');
  }
}
Run Code Online (Sandbox Code Playgroud)

这是Plunker !!

希望这可以帮助!!

  • 谢谢.经过长时间的搜索,没有关于如何基于路由器插座和子页面构建angular2多步表单向导的结果.这个答案是我的多选项卡表单编辑器中的一个关键原则,其中每个选项卡都是一个单独的组件/页面,但都扩展了一个共同的基础.这允许我在路由器插座周围有导航和提交按钮,并将实际操作委托给页面本身. (2认同)