Created
March 4, 2020 16:22
-
-
Save l0co/9cd90c7ea5f1523b2b13147e849d8377 to your computer and use it in GitHub Desktop.
Angular 9 custom component directive
This file contains hidden or 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 {ComponentFactoryResolver, ComponentRef, Directive, Type, ViewContainerRef} from '@angular/core'; | |
/** | |
* Allows to embed custom components into views. | |
* | |
* ## Usage in template | |
* | |
* ```html | |
* <ng-template appCustomComponent></ng-template> | |
* ``` | |
* | |
* ## Usage in component | |
* | |
* ```typescript | |
* class MyComponentClass { | |
* | |
* @ViewChild(CustomComponentDirective, {static: true}) customComponentContainer: CustomComponentDirective; | |
* | |
* somewhereInCode() { | |
* this.customComponentContainer.set(MyComponentClass); | |
* } | |
* | |
* } | |
* ``` | |
* | |
* @param C Type of dynamic component | |
* @see https://angular.io/guide/dynamic-component-loader | |
*/ | |
@Directive({ | |
selector: '[appCustomComponent]' | |
}) | |
export class CustomComponentDirective<C = any> { | |
private _component?: ComponentRef<C>; | |
constructor( | |
public viewContainerRef: ViewContainerRef, | |
private resolver: ComponentFactoryResolver, | |
) { } | |
get component(): ComponentRef<C> | undefined { | |
return this._component; | |
} | |
cleanup() { | |
if (this._component) { | |
this._component.destroy(); | |
this._component = undefined; | |
this.viewContainerRef.clear(); | |
} | |
} | |
set(component: Type<C>) { | |
this.cleanup(); | |
let configComponentFactory = this.resolver.resolveComponentFactory<C>(component); | |
this._component = this.viewContainerRef.createComponent(configComponentFactory); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment