'How to create angular directive for spinner?
I work on project and used ngx-spinner library and now want to make directive for this spinner and write the HTML code inside directive
<ngx-spinner type="ball-scale-multiple" [fullScreen]="false" size="" style="width: 100px;" bdColor="rgba(0, 0, 0, 0.5)">loading ...</ngx-spinner>
how can i do that
Solution 1:[1]
The solution i found is to create separate component for the spinner
<ngx-spinner type="ball-scale-multiple" [fullScreen]="false" size="larg" style="width: 100px;"
bdColor="rgba(0, 0, 0, 0.2)">
<p style="color: white;"> loading ...</p>
and the directive
import { ComponentFactoryResolver, Directive, ElementRef, Input, OnChanges, OnInit,
SimpleChanges, TemplateRef, ViewContainerRef } from "@angular/core";
import { NgxSpinnerService } from "ngx-spinner";
import { SpinnerComponent } from "../spinner/spinner.component";
@Directive({
selector: '[appSpinner]'
})
export class SpinnerDirective implements OnInit, OnChanges {
@Input('appSpinner') show: boolean;
constructor(private ngxSpinnerService: NgxSpinnerService, private elementRef: ElementRef,
private viewContainerRef:ViewContainerRef, private componentFactoryResolver:ComponentFactoryResolver,
private templateRef:TemplateRef<any>) {
}
ngOnInit(): void {
}
ngOnChanges(changes: SimpleChanges): void {
if(this.show){
this.viewContainerRef.clear()
const spinnerComponent = this.componentFactoryResolver.resolveComponentFactory(SpinnerComponent);
this.viewContainerRef.createComponent(spinnerComponent);
this.ngxSpinnerService.show()
}
else{
this.viewContainerRef.clear()
this.viewContainerRef.createEmbeddedView(this.templateRef)
}
}
}
and use the directive on elements in this way
<div *appSpinner="showSpinner">content</div>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Yasmin-Mohsin |
