SnoopDougg
SnoopDougg

Reputation: 1609

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

Upvotes: 5

Views: 3239

Answers (1)

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657486

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

Upvotes: 5

Related Questions