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

Can you use @ViewChild() or similar with a router-outlet? How if so?

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

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

NOT:
<selector-name></selector-name>

据我所知,这与 ViewChild 功能冲突,但我的组件似乎应该能够像查看选择器标签内的内容一样轻松地查看路由器插座内的内容并与之交互。

例如我试过这个:

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

但很自然地,child 是未定义的,因为这是错误的方式。有没有正确的方法?

我正在尝试使用一项服务来共享数据,但随后 运行 遇到了另一个问题 "expression has changed after it was checked" 我希望在不使用 hack 或启用生产模式的情况下解决这个问题。

您可以利用激活事件来获取路由器插座内实例化组件的引用。

摘自RouterOutlet Docs

A router outlet will emit an activate event any time a new component is being instantiated, and a deactivate event when it is being destroyed.

例子

 @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!!');
  }
}

这是Plunker!!

希望对您有所帮助!!

如果您不重新依附于路线,Madhu 的方法会奏效。似乎激活在重新路由上没有得到 运行。

在包含当前组件的路由器插座上有一个只读 属性。

示例:

 @Component({
  selector: 'my-app',
  template: `<h3 class="title">Basic Angular 2</h3>
  <button (click)="identifyYourself()"></button>
  <router-outlet></router-outlet>
  `
})
export class AppComponent {
  @ViewChild(RouterOutlet) outlet;
  constructor(){}

  identifyYourself() {
    if (outlet && outlet.component) {
      (outlet.component as IIdentify).identify();
    }
  }
}

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

  identify(){
    console.log('Hello, I'm the dashboard!');
  }
}
interface IIdentify {
    identify:()=>void;
}

看这里的例子 看看这个例子

https://stackblitz.com/edit/angular-zluvgc