Last active
April 26, 2020 10:00
-
-
Save negue/5f4435c7e1d2c11449691d342b39cdd5 to your computer and use it in GitHub Desktop.
Lazy Component Loader
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, | |
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