I am trying to create a custom Spinner component for my App, So I have created
spinner.component.ts
export class SpinnerComponent implements AfterViewInit {
@ViewChild("spinner") spinner: ElementRef;
constructor() { }
ngAfterViewInit(): void {
this.spinner.nativeElement.style.display = "none";
}
public show = (): void => { this.spinner.nativeElement.style.display = "block"; };
public hide = (): void => { this.spinner.nativeElement.style.display = "none"; };
}
spinner.component.ts
<img #spinner src="assets/images/dotSpinner.gif" class="loading"/>
And I'm trying to control this spinner in my other components, like
sample.component.ts
import { SpinnerComponent } from "../spinner/spinner.component";
export class SimpleComponent {
private spinner: SpinnerComponent = new SpinnerComponent();
constructor() {}
actionHandler = (data: any): void => {
this.spinner.show();
this.clientActionService.subscribe(
data => {
this.spinner.hide();
this.clientAction = data;
},
err => {
this.spinner.hide();
}
);
}
}
But I'm getting error ERROR TypeError: Cannot read property 'nativeElement' of undefined at SpinnerComponent.show
spinner.component.ts // html code
<img *ngIf="isShowSpinner" src="assets/images/dotSpinner.gif" class="loading"/>
<button (click)="show()"> Show </button>
<button (click)="hide()"> Hide </button>
spinner.component.ts //typescript code
public isShowSpinner: boolean = false;
constructor() { }
public show() { this.isShowSpinner = true; }
public hide() { this.isShowSpinner = false; }
Please try this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With