[Fixed] How to select directive and structural directive with ng-content

Issue

I want to select directive with ng-content. How to do like these.

<ng-content select="I want to select directive"></ng-content>
and
<ng-content select="I want to select structural-directive"></ng-content>

Solution

You can select on attributes directives the same way those directives declare their selectors:

<ng-content select="[myDirective]"></ng-content>

Note that this doesn’t directly select on the directive itself, but rather just on the same attribute as the directive would. In the end both selectors (directive and here) are CSS selectors (well, a subset thereof), and you can use the same selectors for multiple things (even directives). Whether or not any directive applies to the element will be irrelevant so long as the element fulfills the selector.

This property is commonly used for content projection in libraries and applications to both project some content and apply a directive at the same time. In fact, knowing that you can have multiple things select on the same thing can be a powerful tool to modularize behavior.


With structural directives this is trickier. Structural directives are syntactic sugar for the compiler, and they desugar to a ng-template with an attribute directive. But ng-template aren’t put into the DOM on their own (the structural directives does this dynamically). The compiler needs to know what to project at compile time, but the directive decides at runtime whether, when and even what to render, so you cannot select on that.

You can read more on how that syntactic sugar works here.

Leave a Reply

(*) Required, Your email will not be published