Angular2: dynamically loading components from a service response

I know this is not the best solution, but I would like to dynamically load components from a JSON response, something like this:

app.component

@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(); } } 

app.service

 @Injectable() export class AppService { component = { title: 'Example component', selector: '<example></example>' } getComponent() { return this.component; } } 

example.component

 @Component({ selector: 'example', template: 'This a example component' }) export class ExampleComponent { } 

If I run this example, my output is <example></example> , but it does not actually display the component. I also tried using [innerHtml]="component.selector" , but that didn't work either. Does anyone have an idea or suggestion?

+7
angular
source share
1 answer

Update

The code for creating the components has changed a bit. A working example can be found in Angular 2 dynamic tabs using custom components


To dynamically insert a component, 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 selected components selected by the user.

In your example, you can use it as

 @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; } } 
+6
source share

All Articles