Last active
July 29, 2021 10:34
-
-
Save isc30/3066aab45ab4687691a059195e55f3b1 to your computer and use it in GitHub Desktop.
Angular Dynamic Component
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, ComponentFactoryResolver, Input, OnInit, ViewContainerRef, Type, AfterViewInit, ComponentRef, ChangeDetectorRef, ViewChild, TemplateRef, Injector } from '@angular/core'; | |
import { checkRequiredInputs, Required } from '../../decorators/required.decorator'; | |
export interface DynamicComponentModel<T = unknown> | |
{ | |
type: Type<T>; | |
inputs?: Partial<T>; | |
} | |
@Component({ | |
selector: 'app-dynamic', | |
template: '<ng-container #target></ng-container><ng-template #content><ng-content></ng-content></ng-template>' | |
}) | |
export class DynamicComponent implements OnInit, AfterViewInit | |
{ | |
@ViewChild('target', { read: ViewContainerRef }) private target!: ViewContainerRef; | |
@ViewChild('content') private content!: TemplateRef<unknown>; | |
private cmpRef?: ComponentRef<unknown>; | |
private isViewInitialized = false; | |
@Input() @Required() model!: DynamicComponentModel; | |
constructor( | |
private componentFactoryResolver: ComponentFactoryResolver, | |
private cdRef: ChangeDetectorRef, | |
private injector: Injector | |
) { } | |
ngOnInit(): void | |
{ | |
checkRequiredInputs(this); | |
} | |
updateComponent() | |
{ | |
if (!this.isViewInitialized) | |
{ | |
return; | |
} | |
if (this.cmpRef == null | |
|| !(this.cmpRef.instance instanceof this.model.type)) | |
{ | |
this.cmpRef?.destroy(); | |
this.target.clear(); | |
const factory = this.componentFactoryResolver.resolveComponentFactory(this.model.type); | |
this.cmpRef = this.target.createComponent( | |
factory, 0, this.injector, | |
[ this.content.createEmbeddedView(this).rootNodes ]); | |
} | |
Object.assign(this.cmpRef.instance, this.model.inputs); | |
this.cdRef.detectChanges(); | |
} | |
ngOnChanges() | |
{ | |
this.updateComponent(); | |
} | |
ngAfterViewInit() | |
{ | |
this.isViewInitialized = true; | |
setTimeout(() => this.updateComponent(), 0); // defer initial render | |
} | |
ngOnDestroy() | |
{ | |
this.cmpRef?.destroy(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment