簡體   English   中英

Angular2如何將父組件注入指令只有它在那里?

[英]Angular2 how to inject parent component into directive only if it's there?

我的自定義表組件有一個select-all指令。 我希望我的指令的用戶能夠以兩種方式實例化它:

1:

<my-custom-table>
    <input type="checkbox" my-select-all-directive/>
</my-custom-table>

2:

<input type="checkbox" [table]="myTableRef" my-select-all-directive/>
<my-custom-table #myTableRef></my-custom-table>

我能夠通過在我的指令構造函數中使用Host,Inject和forwardRef來獲得第一種方法:

constructor(@Host() @Inject(forwardRef(() => MyCustomTableComponent)) table?: MyCustomTableComponent) {
    this.table = table; //later I can call this.table.selectAll();
}

但是當我以第二種方式實例化它時,我得到一個異常,抱怨沒有MyCustomTableComponent的提供者,大概是因為MyCustomTableComponent不是第二種實例化方式的父級,所以Host和forwardRef什么都不返回...

如何使該參數可選? 所以我的指令使用其父或祖父母MyCustomTableComponent(如果存在),或者使用傳遞給它的任何表作為輸入...

您可以使用@Optional()裝飾@Optional()依賴項可選:

constructor(@Optional() @Host() @Inject(forwardRef(() => MyCustomTableComponent)) table?: MyCustomTableComponent) {
    this.table = table; //later I can call this.table.selectAll();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM