import { Component, AfterViewInit, OnDestroy, ViewChild, ComponentFactoryResolver, ApplicationRef, Injector, Inject, PLATFORM_ID } from '@angular/core'
import { CdkPortal, DomPortalOutlet } from '@angular/cdk/portal'
import { isPlatformBrowser } from '@angular/common'
@Component({
    moduleId: module.id+'',
    selector: 'after-content-portal',
    template: `
        <ng-container *cdkPortal>
            <ng-content></ng-content>
        </ng-container>
    `
})
export class AfterContentPortal implements AfterViewInit, OnDestroy {

    @ViewChild(CdkPortal)

    private portal: CdkPortal
    private host: DomPortalOutlet

    constructor(
        @Inject(PLATFORM_ID) private platform_id,
        private cfr: ComponentFactoryResolver,
        private appRef: ApplicationRef,
        private injector: Injector
    ) {

    }
    ngAfterViewInit() {

        if(isPlatformBrowser(this.platform_id)) {

            this.host = new DomPortalOutlet(
                document.querySelector('#afterContentPortal'),
                this.cfr,
                this.appRef,
                this.injector
            )
    
            this.host.attach(this.portal)
        }
    }
    
    ngOnDestroy() {

        if(isPlatformBrowser(this.platform_id)) {
            
            if(!!document.querySelector('#afterContentPortal')) {
    
                this.host.detach()
            }
        }
    }
}