import { ComponentFactoryResolver, ComponentFactory, ComponentRef, Directive, ElementRef, Input, OnInit, Renderer2, ViewContainerRef, HostBinding, } from "@angular/core"; import { ComponentStatus, ComponentSize } from "./shared"; import { SpinnerComponent } from "./spinner.component"; @Directive({ selector: "[pSpinner]" }) export class SpinnerDirective implements OnInit { private shouldShow = false; spinner: ComponentRef; componentFactory: ComponentFactory; /** * Spinner message shown next to the icon */ @Input("pSpinnerMessage") spinnerMessage: string; /** * Spinner status color * `basic`, `primary`, `info`, `success`, `warning`, `danger`, `control`. */ @Input("pSpinnerStatus") spinnerStatus: ComponentStatus = "basic"; /** * Spinner size. Possible values: `tiny`, `small`, `medium` (default), `large`, `giant` */ @Input("pSpinnerSize") spinnerSize: ComponentSize = "medium"; /** * Directive value - show or hide spinner */ @Input("pSpinner") set nbSpinner(val: boolean) { if (this.componentFactory) { if (val) { this.show(); } else { this.hide(); } } else { this.shouldShow = val; } } @HostBinding("class.p-spinner-container") isSpinnerExist = false; constructor( private directiveView: ViewContainerRef, private componentFactoryResolver: ComponentFactoryResolver, private renderer: Renderer2, private directiveElement: ElementRef ) {} ngOnInit() { this.componentFactory = this.componentFactoryResolver.resolveComponentFactory( SpinnerComponent ); if (this.shouldShow) { this.show(); } } hide() { if (this.isSpinnerExist) { this.directiveView.remove(); this.isSpinnerExist = false; } } show() { if (!this.isSpinnerExist) { this.spinner = this.directiveView.createComponent( this.componentFactory ); this.setInstanceInputs(this.spinner.instance); this.spinner.changeDetectorRef.detectChanges(); this.renderer.appendChild( this.directiveElement.nativeElement, this.spinner.location.nativeElement ); this.isSpinnerExist = true; } } setInstanceInputs(instance: SpinnerComponent) { instance.message = this.spinnerMessage; typeof this.spinnerStatus !== "undefined" && (instance.status = this.spinnerStatus); typeof this.spinnerSize !== "undefined" && (instance.size = this.spinnerSize); } }