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

白昼怎懂夜的黑 提交于 2019-12-10 15:20:10

问题


I have a select-all directive for my custom table component. I'd like a user of my directive to be able to instantiate it in two ways:

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>

I was able to get the first way working through the use of Host, Inject, and forwardRef in my directive's constructor:

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...

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...


回答1:


You can make a dependency optional using the @Optional() decorator:

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


来源:https://stackoverflow.com/questions/39082634/angular2-how-to-inject-parent-component-into-directive-only-if-its-there

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!