Last active
June 26, 2017 04:15
-
-
Save wphax/14570328483baff3d8f79eab675704f2 to your computer and use it in GitHub Desktop.
Dynamic Component Loading in Angular 2 RC4
This file contains 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 { DynamicHTMLDirective } from './dynamic-html.directive'; | |
@Component( { | |
selector: 'main-layer', | |
directives: [ DynamicHTMLDirective ], | |
template: '<dynamic-html-wrap [src]="data"></dynamic-html-wrap>' | |
} ) | |
export class AppComponent { | |
public data: string = '<something></something>'; | |
constructor() {} | |
} |
This file contains 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 { Directive, Component, Input, ViewContainerRef, ComponentResolver, ComponentMetadata, ReflectiveInjector, ComponentFactory } from '@angular/core'; | |
import { SomethingComponent } from './something-component'; | |
@Directive( { | |
selector: 'dynamic-html-wrap' | |
} ) | |
export class DynamicHTMLDirective { | |
@Input() src: string; | |
constructor( private vcRef: ViewContainerRef, private resolver: ComponentResolver ) {} | |
createComponentFactory( resolver: ComponentResolver, metadata: ComponentMetadata ) { | |
const cmpClass = class DynamicComponent {}; | |
const decoratedCmp = Component( metadata )( cmpClass ); | |
return resolver.resolveComponent( decoratedCmp ); | |
} | |
ngOnChanges() { | |
if (!this.src) return; | |
const metadata = new ComponentMetadata( { | |
selector: 'dynamic-html', | |
directives: [ SomethingComponent ], | |
template: this.src, | |
} ); | |
this.createComponentFactory( this.resolver, metadata ) | |
.then( factory => { | |
const injector = ReflectiveInjector.fromResolvedProviders( [], this.vcRef.parentInjector ); | |
this.vcRef.createComponent( factory, 0, injector, [] ); | |
} ); | |
} | |
} |
This file contains 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'; | |
@Component( { | |
selector: 'something', | |
template: '<p>Testing: {{data}}</p>' | |
} ) | |
export class SomethingComponent { | |
public data: string = 'Hello world!'; | |
constructor() {} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://fromjami.com/2017/06/26/load-components-dynamically-at-runtime-in-angular-4/