Last active
March 11, 2019 19:05
-
-
Save wesleygrimes/4a8aa712242cadb27a6cae11fd187460 to your computer and use it in GitHub Desktop.
Dynamic Content Outlet Component
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 { | |
| Component, | |
| ComponentRef, | |
| Input, | |
| OnChanges, | |
| OnDestroy, | |
| ViewChild, | |
| ViewContainerRef | |
| } from '@angular/core'; | |
| import { DynamicContentOutletService } from './dynamic-content-outlet.service'; | |
| @Component({ | |
| selector: 'app-dynamic-content-outlet', | |
| template: ` | |
| <ng-container #container></ng-container> | |
| ` | |
| }) | |
| export class DynamicContentOutletComponent implements OnDestroy, OnChanges { | |
| @ViewChild('container', { read: ViewContainerRef }) | |
| container: ViewContainerRef; | |
| @Input() componentName: string; | |
| private component: ComponentRef<{}>; | |
| constructor(private dynamicContentService: DynamicContentOutletService) {} | |
| async ngOnChanges() { | |
| await this.renderComponent(); | |
| } | |
| ngOnDestroy() { | |
| this.destroyComponent(); | |
| } | |
| private async renderComponent() { | |
| this.destroyComponent(); | |
| this.component = await this.dynamicContentService.GetComponent( | |
| this.componentName | |
| ); | |
| this.container.insert(this.component.hostView); | |
| } | |
| private destroyComponent() { | |
| if (this.component) { | |
| this.component.destroy(); | |
| this.component = null; | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment