Skip to content

Instantly share code, notes, and snippets.

@wphax
Last active June 26, 2017 04:15
Show Gist options
  • Save wphax/14570328483baff3d8f79eab675704f2 to your computer and use it in GitHub Desktop.
Save wphax/14570328483baff3d8f79eab675704f2 to your computer and use it in GitHub Desktop.
Dynamic Component Loading in Angular 2 RC4
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() {}
}
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, [] );
} );
}
}
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