[英]Angular2 how to inject parent component into directive only if it's there?
I have a select-all directive for my custom table component. 我的自定义表组件有一个select-all指令。 I'd like a user of my directive to be able to instantiate it in two ways:
我希望我的指令的用户能够以两种方式实例化它:
1: 1:
<my-custom-table>
<input type="checkbox" my-select-all-directive/>
</my-custom-table>
2: 2:
<input type="checkbox" [table]="myTableRef" my-select-all-directive/>
<my-custom-table #myTableRef></my-custom-table>
I was able to get the first way working through the use of Host, Inject, and forwardRef in my directive's constructor: 我能够通过在我的指令构造函数中使用Host,Inject和forwardRef来获得第一种方法:
constructor(@Host() @Inject(forwardRef(() => MyCustomTableComponent)) table?: MyCustomTableComponent) {
this.table = table; //later I can call this.table.selectAll();
}
But when I instantiate it the second way, I get an exception that complains that there is no provider for MyCustomTableComponent, presumably because MyCustomTableComponent isn't the parent in the second way of instantiation, so Host and forwardRef return nothing... 但是当我以第二种方式实例化它时,我得到一个异常,抱怨没有MyCustomTableComponent的提供者,大概是因为MyCustomTableComponent不是第二种实例化方式的父级,所以Host和forwardRef什么都不返回...
How can I make that parameter optional? 如何使该参数可选? So my directive uses its parent or grandparent MyCustomTableComponent if it exists, or otherwise uses whatever table is passed to it as input...
所以我的指令使用其父或祖父母MyCustomTableComponent(如果存在),或者使用传递给它的任何表作为输入...
You can make a dependency optional using the @Optional()
decorator: 您可以使用
@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.