I'm stuck on a hard stuff about Angular Content Projection. I would like to project a component A into another one B and bind some properties on the component A.
For example, I have a SwitchButton component (with several choices). I want this component to display either texts or images.
To do so, here is my SwitchButtonComponent (HTML):
<div class="container border rounded bg-white">
<div class="row text-center">
<div *ngFor="let it of items" class="col" style="cursor:pointer;">
{{it}}
</div>
</div>
</div>
I omitted the ts class, no need here, but of course it has an items property. I use this component in another one like so:
<div>
<switch-button [items]="['A','B','C']"></switch-button>
</div>
Well, this is the easy case. It works fine.
Now, I have a more complex object in items and I want to display an image. It will give:
<div>
<switch-button [items]="[{path:'./img1.png'},{path:'./img2.png'}]">
<img-component></img-component>
</switch-button>
</div>
The img-component is just a simple component rendering an image and having one property: the imgPath.
And in the SwitchButtonComponent:
<div class="container border rounded bg-white">
<div class="row text-center">
<div *ngFor="let it of items" class="col" style="cursor:pointer;">
<ng-content></ng-content>
</div>
</div>
</div>
Here you can see I can't bind the imgPath property of the projected component (img-component).
Do you have some ideas guys ?
I don't know if this is possible using ng-content
. I solved it using <ng-container>
(if that is ok with your requirements):
SwitchButtonComponent:
<div class="container border rounded bg-white">
<div class="row text-center">
<div *ngFor="let it of items" class="col" style="cursor:pointer;">
<ng-container [ngTemplateOutlet]="template" [ngTemplateOutletContext]="{ $implicit: it }"></ng-container>
</div>
</div>
</div>
AppComponent:
<div>
<switch-button [items]="[{path:'./img1.png'},{path:'./img2.png'}]">
<ng-template let-item>
<img-component [item]="item"></img-component>
</ng-template>
</switch-button>
</div>
ImageComponent:
<div>{{ item.path }}</div>
...
@Input()
item: any;
Here is Stackblitz example demonstrating this.
Hope this helps.