Answer the question
In order to leave comments, you need to log in
Angular 2 how to set template dynamically?
I have a component, I want to set completely different templates for it depending on the parameters passed to it, how can I do this?
Answer the question
In order to leave comments, you need to log in
See this answer How to initialize router in Angular2?
It's a bit outdated code
1) Using the compiler
Create a directive that will dynamically load a component with the desired template
@Directive({ selector: 'html-outlet' })
export class HtmlOutlet {
@Input() html: string;
cmpRef: ComponentRef<any>;
constructor(private vcRef: ViewContainerRef, private compiler: Compiler) { }
ngOnChanges() {
const html = this.html;
if (!html) return;
if(this.cmpRef) {
this.cmpRef.destroy();
}
@Component({
selector: 'dynamic-comp',
template: html
})
class DynamicHtmlComponent {};
@NgModule({
imports: [CommonModule],
declarations: [DynamicHtmlComponent]
})
class DynamicHtmlModule {}
this.compiler.compileModuleAndAllComponentsAsync(DynamicHtmlModule)
.then(factory => {
const moduleRef = factory.ngModuleFactory.create(this.vcRef.parentInjector);
const compFactory = factory.componentFactories.find(x => x.componentType === DynamicHtmlComponent);
const cmpRef = this.vcRef.createComponent(compFactory, 0, moduleRef.injector);
});
}
ngOnDestroy() {
if(this.cmpRef) {
this.cmpRef.destroy();
}
}
}
template
maybe templateUrl
Parameters @Input
@Output
can be screwed up later if necessary entryComponents
an array of your module or componentANALYZE_FOR_ENTRY_COMPONENTS
providerDidn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question