简体   繁体   中英

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

Somewhere on the web I saw a tutorial about creating a tab component in it used this awesomely simple pattern

// TABS COMPONENT

export class TabsComponent{
    tabs: TabItemComponent[];

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

// TAB ITEM COMPONENT

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

// VIEW

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

Really cool and clean pattern to get the parent injected into the child

now, this works fine when the parent is actually there in the view... so perfect for tabs...

a little less perfect for ButtonGroupComponent and ButtonComponent scenario, where Button can be standalone and not necessarily wrapped in the Button Group

I have similar pattern there with an exception

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

But, if the button is standalone this does not work, I get an error:

ERROR Error: Uncaught (in promise): Error: No provider for ButtonGroupComponent!

Any ideas how to prevent the error in the constructor?

You can decorate the argument with @Optional() . See the documentation .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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