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; } }
Günter zöchbauer
source share