Skip to content
Loading
How to dynamically inject component in Angular2 ?
 
  1. import { Component,  ViewChild, ViewContainerRef, ComponentRef } from "@angular/core";  
  2.   
  3. @Component({  
  4.     moduleId: module.id,  
  5.     selector: 'dyanmic-template',  
  6.     templateUrl: 'dynamictemplate.html'  
  7. })  
  8.   
  9. export class DynamicTemplate2Component implements OnInit {  
  10.   
  11.    @ViewChild("container", { read: ViewContainerRef }) private container: ViewContainerRef;  
  12.  private cmpRef: any;  
  13.   
  14. constructor(private viewContainer: ViewContainerRef) {  
  15.           
  16.     }  
  17.   
  18. ngOnInit(): void {}  
  19.   
  20. public loadPageUrl(index: number): void {  
  21.         if (!HelperService.isNullOrEmpty(this._templateData)) {  
  22.             if (!HelperService.isNullOrEmpty(this.cmpRef)) {  
  23.                 this.cmpRef.destroy();  
  24.             }  
  25.             let item = { data: this._templateData[index], index: index };  
  26.             this.onTemplateload(item);  
  27.         }  
  28.         else {  
  29.             this._defaultIndex = index;  
  30.         }  
  31.     }  
  32.   
  33.     private onTemplateCLoad(item: any): void {  
  34.         this._currentTemplate =(item.data);          
  35.         this.setTemplateVisible(true);  
  36.         this.loadTemplate(item.data.componentObject);  
  37.         this.onTemplateRowClick.emit(this._currentTemplate);  
  38.     }  
  39.   
  40. private loadTemplate(factory: any): void {  
  41.         this.cmpRef = this.container.createComponent(factory);  
  42.     }  
  43.   
  44. }  
Hope this will help you. 
0