Last active
February 10, 2017 10:58
-
-
Save aegyed91/d9d65e8c688a7ac526e25602a9a086db to your computer and use it in GitHub Desktop.
Angular 2 dynamic component creation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Component, Directive, TemplateRef, ViewContainerRef, Injector, | |
ComponentFactoryResolver, Renderer } from '@angular/core'; | |
@Component({ | |
selector: 'alert', | |
template: ` | |
<div class="alert alert-success" role="alert"> | |
<ng-content></ng-content> | |
</div> | |
` | |
}) | |
export class AlertComponent { | |
} | |
@Directive({ selector: 'template[alert]' }) | |
export class AlertDirective { | |
constructor( | |
templateRef: TemplateRef, | |
viewContainerRef: ViewContainerRef, | |
injector: Injector, | |
componentFactoryResolver: ComponentFactoryResolver, | |
renderer: Renderer | |
) { | |
this.templateRef = templateRef; | |
this.viewContainerRef = viewContainerRef; | |
this.injector = injector; | |
this.componentFactoryResolver = componentFactoryResolver; | |
this.renderer = renderer; | |
} | |
ngOnInit() { | |
this._windowFactory = this.componentFactoryResolver.resolveComponentFactory(AlertComponent); | |
const nodes = this.getContentNodes(this.templateRef); | |
this._windowRef = this.viewContainerRef.createComponent(this._windowFactory, 0, this.injector, nodes); | |
console.log('This is your AlertComponent instance: ', this._windowRef.instance); | |
} | |
getContentNodes(content) { | |
if (!content) { | |
return []; | |
} else if (content instanceof TemplateRef) { | |
return [this.viewContainerRef.createEmbeddedView(content).rootNodes]; | |
} else { | |
return [[this.renderer.createText(null, `${content}`)]]; | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Component } from '@angular/core'; | |
import { AlertDirective, AlertComponent } from '../directives/smth.directive'; | |
@Component({ | |
selector: 'home-page', | |
directives: [AlertComponent, AlertDirective], | |
precompile: [AlertComponent], | |
template: ` | |
<div> | |
<p *ngFor="let alert of alerts"> | |
<template alert>{{ alert }}</template> | |
</p> | |
<button class="btn btn-primary" (click)="addAlert()">Add Alert</button> | |
</div> | |
` | |
}) | |
export class HomePageComponent { | |
alerts = []; | |
addAlert() { | |
this.alerts.push('This is a dynamically created alert component.'); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment