【问题标题】:How to get parent/host of routed component如何获取路由组件的父/主机
【发布时间】:2016-03-31 06:43:54
【问题描述】:

假设我们有带有该模板的 ComponentA:

 <div>
       <router-outlet></router-outlet>
 </div>

ComponentA 有 routeConfig 来路由到 ComponentB。

如何从路由的componentB中获取ComponentA?

我尝试将@Host 注入到 ComponentB,但出现异常。

【问题讨论】:

    标签: angular angular2-routing


    【解决方案1】:

    路由器使用DynamicComponentLoader 添加组件。这样的组件能力有限(没有@Input()可以通过,@Host()不能用)。

    您可以使用共享服务,其中ComponentA 将自己传入,ComponentB 可以读取该值。

    Update parent component title from routed child component in Angular 2 此处解释了类似的用例。该服务不必是全球性的。也可以通过将其添加到ComponentAproviders: [MySharedService] 而不是bootstrap() 来仅在父母和孩子之间共享,如链接答案所示。

    【讨论】:

    • 您是否建议扩展 RouterOutlet 并管理路由映射以跟踪路由更改?我发现很难知道路由的组件树是什么。
    • 扩展RouterOutlet似乎是一种常见的做法,我自己还没有做过。另一种方法是创建共享服务,注入constructor(router:Router) 并订阅router.subscribe(...) 以获取有关路由更改的通知。
    猜你喜欢
    • 1970-01-01
    • 2018-01-11
    • 2018-11-14
    • 2018-06-12
    • 2018-02-04
    • 2017-05-24
    • 1970-01-01
    • 2021-10-14
    • 1970-01-01
    相关资源
    最近更新 更多