I'm aware this is not the best solution but I would like to be able to load components dynamically from a JSON response, something along these lines:
@Component({
selector: 'my-app',
template: '<h1>My First Angular 2 App</h1> {{component.title}} {{component.selector}}',
providers: [AppService],
directives: [ExampleComponent]
})
export class AppComponent implements OnInit {
component:{};
constructor(
private _appService: AppService) {
}
ngOnInit() {
this.component = this._appService.getComponent();
}
}
@Injectable()
export class AppService {
component = {
title: 'Example component',
selector: '<example></example>'
}
getComponent() {
return this.component;
}
}
@Component({
selector: 'example',
template: 'This a example component'
})
export class ExampleComponent {
}
If I run this example, my output is <example></example>
but it doesn't actually render the component. Also I've tried to use [innerHtml]="component.selector"
, but that also didn't work. Does anyone have an idea or suggestion?
update
The code to create components has changed a bit. A working example can be found in Angular 2 dynamic tabs with user-click chosen components
To insert a component dynamically you can use ViewContainerRef.createComponent()
For a declarative approach you can use a helper component like
@Component({
selector: 'dcl-wrapper',
template: `<div #target></div>`
})
export class DclWrapper {
@ViewChild('target', {read: ViewContainerRef}) target;
@Input() type;
cmpRef:ComponentRef;
private isViewInitialized:boolean = false;
constructor(private resolver: ComponentResolver) {}
updateComponent() {
if(!this.isViewInitialized) {
return;
}
if(this.cmpRef) {
this.cmpRef.destroy();
}
this.resolver.resolveComponent(this.type).then((factory:ComponentFactory<any>) => {
this.cmpRef = this.target.createComponent(factory)
});
}
ngOnChanges() {
this.updateComponent();
}
ngAfterViewInit() {
this.isViewInitialized = true;
this.updateComponent();
}
ngOnDestroy() {
if(this.cmpRef) {
this.cmpRef.destroy();
}
}
}
See also Angular 2 dynamic tabs with user-click chosen components
In you example you can use it like
@Component({
selector: 'my-app',
template: '<h1>My First Angular 2 App</h1> {{component.title}} <dcl-wrapper [type]="component.type"></dcl-wrapper>',
providers: [AppService],
directives: [ExampleComponent]
})
export class AppComponent implements OnInit {
component:{};
constructor(
private _appService: AppService) {
}
ngOnInit() {
this.component = this._appService.getComponent();
}
}
import {ExampleComponent} from './example.component.ts';
@Injectable()
export class AppService {
component = {
title: 'Example component',
type: ExampleComponent
}
getComponent() {
return this.component;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With