SnoopDougg SnoopDougg - 3 months ago 20
TypeScript Question

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

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

Answer

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();
}
Comments