I am struggling to access a 'child' directive within a structural directive in order to pass some data into that directive. Unfortunately, I keep getting undefined or an injection error.
Here is the HTML snippet I have:
<app-table [dataSource]="data">
<button *customColumn="let row" [highlightRowOnClick]="row">
click here!
</button>
</app-table>
I aim to inject all rows using the customColumn
directive into the [highlightRowOnClick]
directive so that clicking on one row will deselect all other rows.
The flow of passing rows to the directive should be:
(app-table
--> *customColumn
--> [highlightRowOnClick]
).
I have set up a Stackblitz to showcase this issue with row selection functioning correctly but not with row deselection.
My Thoughts
I am aware that accessing child components via
@ContentChildren
is not possible due to the[highlightRowOnClick]
directive not being a direct child, rather a sibling in the view (read more here).A structural directive can select its host element (e.g., an attribute directive like ngSwitch) through the
@Host
decorator, but it doesn't work the other way around, leading to an Injector error (
). (Details available here)no provider for 'customColumn' found
Using a service to inject the data could cause bugs when multiple tables exist in the current view since the service is a singleton and overlapping rows could create unexpected selection issues (like selections happening in both tables).
Directly injecting the rows into the
[highlightRowOnClick]
directive would require manual intervention by the programmer each time. It seems logical to only highlight the current row and not expose all rows at that level since they are already accessible via[dataSource]
. Therefore, this might not be the optimal solution.
Example:
<app-table [dataSource]="rows">
<button *customColumn="let row; let rows=rows" [highlightRowOnClick]="row" allRows="rows">
click here!
</button>
</app-table>
Is there a better approach to resolve this dilemma? Perhaps a completely different strategy?