Home > database >  Placing content children inside component's subcomponent
Placing content children inside component's subcomponent

Time:01-17

I have the following:

Component.html

<container-component>
    <item-component *ngFor="let item of contentItems">
        <! -- render content child here -->
    </item-component>     
</container-component>

Component.ts

...
selector: 'component'
...
@ContentChildren(ItemComponent) contentItems: QueryList<ItemComponent>;

ItemComponent.ts

...
selector: 'item-component'
...

Usage:

<component>
    <content></content>
</component>

I have a component that should dynamically generate wrap content children (<content>) inside its item-components).

I tried making the item-components a ViewChildrenRef of ItemComponents and placing each of the contentItems in as a View using createEmbeddedRef. That didn't work since Angular doesn't recognize contentItems as TemplateRefs.

How would I do this? Thanks in advance.

CodePudding user response:

Why don't you pass contentItems from container-component to item-component:

<item-component [items]="contentItems">

And then in item-component ts accept it:

@Input() items;

And in template put:

<ng-container *ngFor="let item of items">
    <! -- render content child here -->
</ng-container> 

?

CodePudding user response:

I solved it by getting an instance of <content>'s TemplateRef using a template reference variable for all of <content>'s template and then using that in Component's template in a <ng-template>:

Component.html

<container-component>
    <item-component *ngFor="let item of contentItems">
        <ng-template [ngTemplateOutlet]="item.templateRef"></ng-template>
    </item-component>     
</container-component>

Content.ts

...
@ViewChild('itemTemplate') itemTemplate;
...

Content.html

<ng-container #itemTemplate>
    <!-- content stuff -->
</ng-container>
  •  Tags:  
  • Related