繁体   English   中英

Angular4:在构造函数中注入父组件 - 使其失败安全

[英]Angular4: Injecting parent component in the constructor - making it fails safe

在网络的某个地方,我看到了一个关于在其中创建选项卡组件的教程,使用了这个非常简单的模式

// TABS COMPONENT

export class TabsComponent{
    tabs: TabItemComponent[];

    addTab(tab: TabItemComponent){
        this.tabs.push(tab);
    }
}

// TAB项目组件

export class TabItemComponent{
    constructor(private tabsComponent: TabsComponent){
        this.tabsComponent.addTab(this);
    }
}

//查看

<tabs>
    <tab-item>text 1</tab-item>
    <tab-item>Text 2</tab-item>
</tabs>

非常凉爽和干净的模式,让父母注入孩子

现在,当父视图在视图中实际存在时,这可以正常工作...非常适合制表符...

对ButtonGroupComponent和ButtonComponent场景来说不太完美,其中Button可以是独立的,不一定包含在Button Group中

我有类似的模式有一个例外

constructor(private buttonGroup: ButtonGroupComponent) {
  if (this.buttonGroup) {
    this.buttonGroup.addButton(this);
  }
}

但是,如果按钮是独立的,这不起作用,我收到一个错误:

错误错误:未捕获(承诺):错误:没有ButtonGroupComponent的提供程序!

任何想法如何防止构造函数中的错误?

您可以使用@Optional()修饰参数。 请参阅文档

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM