Home > Software design >  Can I select ng-content within ng-container (or otherwise)?
Can I select ng-content within ng-container (or otherwise)?

Time:01-14

I have a component with an ng-content that selects a specific element but when I wrap the element in an ng-container, it does not render.

I need the select of the ng-content to be specific so that I can exclude rendering of other elements so I can keep the code clean and as intended.

Component:

<ng-content select="input"></ng-content>

Content:

<input id="1" />
<input id="2" />
<ng-container *ngIf="condition"> <!-- Condition has a thruthy value -->
    <input [id]="item   2" *ngFor="let item of [1, 2, 3, 4]" />
</ng-container>

Output

<input id="1" />
<input id="2" />

Expected output

<input id="1" />
<input id="2" />
<input id="3" />
<input id="4" />
<input id="5" />
<input id="6" />

I tried both with ng-container and ng-template but neither seems to work.

Does anyone have an idea how to resolve this or if it even is possible?

CodePudding user response:

Accomplish this with the ngProjectAs attribute

<ng-container ngProjectAs="input" *ngIf="true"> <!-- Condition has a thruthy value -->
  <input [id]="item   2" *ngFor="let item of [1, 2, 3, 4]" />
</ng-container>
<ng-content select="input"></ng-content>
  • Related