You can do this already if you wrap the content with a <template>
element.
// renders the template
// `item` is just an example how to bind properties of the host component to the content passed as template
@Directive({
selector: '[templateWrapper]'
})
export class TemplateWrapper implements OnChanges {
private embeddedViewRef:EmbeddedViewRef<any>;
@Input()
private item:any;
constructor(private viewContainer:ViewContainerRef) {
console.log('TemplateWrapper');
}
@Input() templateWrapper:TemplateRef<any>;
ngOnChanges(changes:{[key:string]:SimpleChange}) {
if (changes['templateWrapper']) {
if (this.embeddedViewRef) {
this.embeddedViewRef.destroy();
}
console.log('changes', changes);
this.embeddedViewRef = this.viewContainer.createEmbeddedView(this.templateWrapper, {item: this.item});
}
if (this.embeddedViewRef) {
console.log('context', this.embeddedViewRef.context);
this.embeddedViewRef.context.item = this.item;
}
}
}
// just some component that is used in the passed template
@Component({
selector: 'test-component',
styles: [':host { display: block; border: solid 2px red;}'],
directives: [TemplateWrapper],
template: `
<div>test-comp</div>
<div>prop: {{prop | json}}</div>
`
})
export class TestComponent {
@Input() prop;
constructor() {
console.log('TestComponent');
}
}
// the component the `<template>` is passed to to render it
@Component({
selector: 'some-comp',
directives: [TemplateWrapper],
template: `
<div>some-comp</div>
<div *ngFor="let f of fields">
<div [ngSwitch]="f.type">
<span *ngSwitchCase="'custom'">
<template [templateWrapper]="template" [item]="f" ></template>
</span>
</div>
</div>
`
})
export class SomeComponent {
constructor() {
console.log('SomeComponent');
}
@ContentChild(TemplateRef) template;
fields = [
{name: 'a', type: 'custom'},
{name: 'b', type: 'other'},
{name: 'c', type: 'custom'}];
}
// the component where the `<template>` is passed to another component
@Component({
selector: 'my-app',
directives: [SomeComponent, TestComponent],
template: `
<some-comp>
<template let-item="item">
<div>some content</div>
<div>item: {{item | json}}</div>
<test-component [prop]="item"></test-component>
</template>
</some-comp>
`,
})
export class App {
constructor() {
console.log('AppComponent');
}
}
Plunker example