Add Component dynamically in Angular 2

2017-01-07 11:18:21

How to bind component to another one in Angular 2

Some times we need to bind custom components in order to make pages easy managable.

for example you have AComponent & BComponent and you need to bind BComponent instead AComponent to HomeComponent in special condition, special days or something else.

So we need to

1-add #suitPlaceForComponent to dom object in HomeComponent html, for example: 

 <div #suitPlaceForComponent></div>

 2-in HomeComponent 

import {  Component, EventEmitter,  ViewContainerRef, ViewChild, AfterContentInit, ComponentFactoryResolver } from '@angular/core';
import {AComponent} from "../AModule/a.component";
import {BComponent} from "../BModule/b.component";

@Component({ selector: 'home', templateUrl: './home.component.html' })

export class HomeComponent implements AfterContentInit{

@ViewChild('suitPlaceForComponent',{read:ViewContainerRef}) suitPlaceForComponent; public cmpRef:any; constructor(public componentFactoryResolver:ComponentFactoryResolver) { }

ngAfterContentInit():void {

if(someCondition){

var component = this.componentFactoryResolver.resolveComponentFactory(AComponent);


}
else { var component = this.componentFactoryResolver.resolveComponentFactory(BCompoenent); }

this.cmpRef = this.suitPlaceForComponent.createComponent(component);

}

}

Attention: if you have HomeModule you must add 

entryComponents:[AComponent,BComponent]

in HomeModule

 

 Some times you need to get some values from AComponent or BComponent and use it in HomeComponent so you can set or get like below

for set:
this.cmpRef.instance.someValue = value;
for get:
this.SomeValueInAComponent = this.cmpRef.instance.someValue;
https://github.com/sadeghipour/universal-ng2-add-component-dynamically

Happy Coding!

Tags Cloud

Angular 2

add component

dynamically

bind

@ViewChild

ComponentFactoryResolver