0

I am using material design and Angular 5. I was trying to use the material loader, so when navigation start show loader and when ends remove loader as per the answer in this question. I tried viewchild by

<mat-progress-bar #spinnerElement [mode]="'indeterminate'" [color]="'primary'"></mat-progress-bar>

and called in my component constructor as below:

@ViewChild('spinnerElement')
spinnerElement: ElementRef;

constructor(
.....
    private ngZone: NgZone,
    private renderer: Renderer) {
        console.log(this.spinnerElement, 'spinnerElement');
    }

But console always returns undefined. Bit new to Angular. Any idea why guys?

2 Answers 2

1

Take a look at angular life cycle.

You can't access your DOM elements in your constructor because they still not rendered.

Try to access your 'spinnerElement' in your ngOnInit().

ngOnInit():

Initialize the directive/component after Angular first displays the data-bound properties and sets the directive/component's input properties. Called once, after the first ngOnChanges().

Sign up to request clarification or add additional context in comments.

Comments

1

Access @ViewChild in ngOnInit(), You can't use it before it is initialized.

1 Comment

No, it's not available in ngOnInit, you have to wait at least for ngAfterViewInit()

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.