[英]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.