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
  • 8,063
  • 5
  • 40
  • 56
chewi
  • 159
  • 2
  • 3
  • 16

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
  • 39,722
  • 10
  • 72
  • 98
Gili Yaniv
  • 3,073
  • 2
  • 19
  • 34
1

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

Saurabh Agrawal
  • 7,581
  • 2
  • 27
  • 51