Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot read property 'nativeElement' of undefined Angular 6

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

like image 564
SjVnyk Avatar asked Nov 07 '22 01:11

SjVnyk


1 Answers

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.

like image 87
Bhavin Avatar answered Nov 14 '22 21:11

Bhavin