I'm trying to implement dynamic components, as described in http://blog.lacolaco.net/post/dynamic-component-creation-in-angular-2/
I'm confused by the solutions rendered useless in each subsequent version of Angular2. I've tried http://blog.lacolaco.net/post/dynamic-component-creation-in-angular-2-rc-5/ only to find out it doesn't compile, then finally invoke pipe during run time using pipe name /metadata which still doesn't make the simple thing that was the original idea: I give the HTML or URL as argument to dynamically compiled component.
This is what I actually have:
import {
Component, Input, ViewContainerRef, ReflectiveInjector,
ViewChild, OnInit, Compiler, NgModule
} from "@angular/core";
import {BrowserModule} from "@angular/platform-browser";
@Component({
selector: 'my-dynamic',
template: `
<div class="my-dynamic">
<div #content></div>
</div>
`
})
export class MyDynamic implements OnInit {
@Input('src') src: string;
@ViewChild('content') content;
constructor(private vcRef: ViewContainerRef, private compiler: Compiler) {
}
ngOnInit() {
const src = this.src
@Component({
selector: 'dynamic-comp',
templateUrl: src
})
class DynamicComponent {
};
@NgModule({
imports: [BrowserModule],
declarations: [DynamicComponent]
})
class DynamicModule {}
this.compiler.compileModuleAndAllComponentsAsync(DynamicModule)
.then(({moduleFactory, componentFactories}) => {
const compFactory = componentFactories.find(x => x.componentType === DynamicComponent);
const injector = ReflectiveInjector.fromResolvedProviders([], this.vcRef.parentInjector);
const cmpRef = this.vcRef.createComponent(compFactory, 0, injector, []);
});
}
}
and how it is called:
@Component({
selector: 'my-app',
template: `
<h1>{{title}}</h1>
<my-dynamic [src]="templateSource"></my-dynamic>
`
})
export class AppComponent implements OnInit, AfterViewInit {
title: string = "Angular Sandbox";
templateSource: string = "/templates/dynamic/dynamic1.htm"
}
Setting the 'template' as arbitrary string works, but with templateUrl, the template gets loaded, but not displayed. There are no errors on console...
Is it possible to create on-the-fly components with arbitrary template urls? Or it won't work that way?