Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save wesleygrimes/4a8aa712242cadb27a6cae11fd187460 to your computer and use it in GitHub Desktop.

Select an option

Save wesleygrimes/4a8aa712242cadb27a6cae11fd187460 to your computer and use it in GitHub Desktop.
Dynamic Content Outlet Component
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