Skip to content

Instantly share code, notes, and snippets.

@negue
Last active April 26, 2020 10:00
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save negue/5f4435c7e1d2c11449691d342b39cdd5 to your computer and use it in GitHub Desktop.
Save negue/5f4435c7e1d2c11449691d342b39cdd5 to your computer and use it in GitHub Desktop.
Lazy Component Loader
import {
Component,
ChangeDetectionStrategy,
ViewChild,
ViewContainerRef,
ComponentFactoryResolver,
Injector, Input, OnChanges, SimpleChanges
} from '@angular/core';
const lazyComponents = {
'lazy-comp': () => import('../lazy-comp/lazy-comp.component'),
'other-comp': () => import('../lazy-comp/other-comp.component')
};
@Component({
selector: 'my-dynamic-loader',
template: `
<ng-container #targetContainer></ng-container>
`,
changeDetection: ChangeDetectionStrategy.OnPush
})
export class DynamicLoaderComponent implements OnChanges {
@Input()
public component: string;
@ViewChild('targetContainer', {read: ViewContainerRef, static: true})
public targetContainer: ViewContainerRef;
constructor (private resolver: ComponentFactoryResolver,
private injector: Injector) {
}
async setComponent () {
const imported = await lazyComponents[this.component]();
const keys = Object.keys(imported);
// get the first object of the imported js-module
const theComp = imported[keys[0]];
const componentFactory = this.resolver.resolveComponentFactory(theComp);
const componentRef = this.targetContainer.createComponent(componentFactory, 0, this.injector);
componentRef.changeDetectorRef.markForCheck();
}
ngOnChanges (changes: SimpleChanges): void {
if (changes['component']) {
this.setComponent();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment