import {
Component,
AfterViewInit,
OnDestroy,
ViewChild,
Input,
ComponentFactoryResolver,
ApplicationRef,
Injector,
TemplateRef
} from '@angular/core';
import {
PortalHost,
DomPortalHost,
ComponentPortal
} from '@angular/cdk/portal';
@Component({
selector: 'bom-portal-host',
template: `
`,
styles: []
})
export class BomPortalHostComponent implements AfterViewInit, OnDestroy {
@Input() selector: string;
@Input() portal: ComponentPortal;
@ViewChild('portalHost', { static: true }) portalRef: TemplateRef;
private host: PortalHost;
constructor(
private cfr: ComponentFactoryResolver,
private appRef: ApplicationRef,
private injector: Injector
) {}
ngAfterViewInit() {
console.log(this.portalRef);
if (!this.selector || !this.portal) {
throw new Error('PortalHost need a DOM element and a ComponentPortal');
}
this.host = new DomPortalHost(
document.querySelector(this.selector),
this.cfr,
this.appRef,
this.injector
);
this.host.attach(this.portal);
}
ngOnDestroy() {
this.host.detach();
}
}