I know this question is old, but hopefully it helps people who are trying similar things.
, , , - . HTML. ng-include - un-sanitized HTML. P.I.T.A, , , ...
, templateRefs, , , ref . . 3 4 , . , .
ref
import { Directive, TemplateRef, Input } from '@angular/core';
@Directive({
selector: 'get-template',
})
export class GetTemplateDirective {
@Input() name: string;
constructor(public template: TemplateRef<any>) { }
}
,
@Component({
selector: 'sub-component-templates',
template: `
<ng-template get-template [name]="tpl1">
Put Whatever here, including other components if you please
</ng-template>
<ng-template get-template [name]="tpl2">
Different template here
</ng-template>
... and so on and so on...
`
})
export class Templates { }
, ,
ng-, , .
, ..
<sub-component>
<sub-component-templates></sub-component-templates>
</sub-component>
import { Component, ViewChild, ContentChildren, QueryList } from '@angular/core';
import { GetTemplateDirective } from 'wherever';
@Component({
selector: 'sub-component',
template: `
<ng-content></ng-content>
<div #templateRenderer></div>
`
})
export class SubComponent {
@ViewChild('templateRenderer',{read:ViewContainerRef}) anchor: ViewContainerRef;
@ContentChildren(GetTemplateDirective) templates: QueryList<GetTemplateDirective>;
ngAfterContentInit() {
... at this stage, you will have access to all the included templates with that directive on them. You can perform your logic to choose which one you want. Once you have selected the proper one, you can embed it like so ...
let desiredTemplateName = 'whatever';
for (let t of this.templates.toArray()) {
if(t.name === desiredTemplateName) {
this.anchor.createEmbeddedView(t.template);
break;
}
}
}
}
, , . ngSwitchCase, . , , , , , 100 ( , ), - .
. , - https://plnkr.co/edit/fdP9Oc?p=info
...
, , . ref...
import { Component, ViewChild, ContentChildren, QueryList, TemplateRef } from '@angular/core';
template: TemplateRef<any>;
, .
Angular 2/4 ... waaaaaay . , , .