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?

Michael Doye
  • 7,713
  • 5
  • 38
  • 54
chewi
  • 159
  • 1
  • 3
  • 15

2 Answers2

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().

eko
  • 37,528
  • 9
  • 64
  • 91
Gili Yaniv
  • 2,623
  • 2
  • 15
  • 33
1

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

Saurabh Agrawal
  • 7,230
  • 2
  • 22
  • 46