ng-content select bound variable

I know this is an old question, but this is one of the first places I landed when searching for this functionality so I’ll add how I was able to solve it.

ngContent is only for static projection, so you can’t use it to do any bindings. If you need bindings in your projected content you can use ngTemplateOutlet and ngOutletContext.

Usage Example:

<my-component>
    <template let-item="item">
        <h1>{{item?.label}}</h1> - <span>{{item?.id}}</span>
    </template>
</my-component>

Inside MyComponent you can access that template using ContentChild:

@ContentChild(TemplateRef) templateVariable: TemplateRef<any>;

Then inside your component’s template you pass that to ngTemplateOutlet like this:

<div *ngFor="let item of list">
    <template [ngTemplateOutlet]="templateVariable" [ngOutletContext]="{item: item}"></template>
</div>

The ngOutletContext is optional but it allows you to create the object that you will be binding to in the template. Notice that I created a property item in the context object. That matches the name I put on the template here: let-item="item"

Now the consumer of my-component can pass in the template to be used for each item in the list.

Credit:
This answer led me in the right direction.

Leave a Comment