【问题标题】:Global component with angular2angular2的全局组件
【发布时间】:2016-12-07 15:56:35
【问题描述】:

是否可以在根组件模板中添加组件并能够从子组件访问它。例如,假设这是根应用程序组件:

<main>
   <global-component #globalComponent></global-component>
   <child-component></child-component>
</main>

我想要的是,在“子组件”的代码中,能够做这样的事情:

@Component({...})
export class ChildComponent
{
    @SomethingAwesome(GlobalComponent) globalComponent: GlobalComponent;
}

目标是能够始终以相同的方式显示错误/警告。 “GlobalComponent”模板将是一个模态消息,我希望能够随时显示它。例如:

...
this.globalComponent.ShowError("Something's weird in here !");
...

我想到的替代方案(我猜)是创建一个带有可观察的服务,“GlobalComponent”会订阅并做出相应的反应,但我想知道我问的是否可能。

编辑:

在示例中,组件是兄弟,但可能并非总是如此。 “GlobalComponent”应该在任何组件中都可用,无论其“深度”如何。

谢谢

【问题讨论】:

    标签: angular


    【解决方案1】:

    如果是兄弟姐妹,直接传进去

    <main>
       <global-component #globalComponent></global-component>
       <child-component [global]="globalComponent"></child-component>
    </main>
    
    @Component({...})
    export class ChildComponent
    {
        @Input() global: GlobalComponent;
    
        ngOnInit() {
          console.log(this.global);
        }
    }
    

    【讨论】:

    • 在我的示例中它们是兄弟姐妹,但目标是能够从任何组件访问“globalComponent”。兄弟姐妹与否。抱歉,如果不清楚。
    • 那么你需要一个共享服务。 GlobalComponent 可以注入共享服务并向服务注册自己,其他访问相同服务的组件可以在那里访问GlobalComponent。更好的选择是在共享服务中使用Observable 并使用它在组件之间进行通信。一个是订阅者,另一个是发射者。
    • 嗯嗯,我就是这么想的……好吧,那我就那样做了。谢谢。
    • 我刚刚做了它,它的工作原理。我将最初的答案标记为已接受,即使它更多的是解决我的问题的评论。谢谢
    猜你喜欢
    • 2016-09-25
    • 1970-01-01
    • 2016-10-06
    • 1970-01-01
    • 2018-01-19
    • 2017-05-30
    • 1970-01-01
    • 2017-06-15
    • 2018-02-13
    相关资源
    最近更新 更多