ElementRef is undefined when using @ViewChild

1.4k views Asked by At
import {Component, ElementRef, HostBinding, ViewChild} from '@angular/core';
export class MainPage {
  constructor(
    el: ElementRef
  ) {
    this.contentElement = el.nativeElement;
  }

  contentElement = null;

@ViewChild('wrapper', { static: true }) wrapper: ElementRef;

this.size = this.wrapper.nativeElement.clientWidth - 36;

result

ERROR TypeError: Cannot read property 'nativeElement' of undefined
console.log(this.wrapper);
=>undefined

in another component , It works well without any initialization.

but I don't know why this component can't work

1

There are 1 answers

1
ukn On BEST ANSWER

The template need to be rendered if you want your ViewChild to not be undefined. Its all about timing. You are trying to use something that doesnt exist yet which is why you are having an error.

You need to use a lifecycle hook that angular provide

In your case, the view need to be rendered first so I would use ngAfterViewInit() with static: false and ngOnInit() with static: true

ngAfterViewInit(): void {
    this.size = this.wrapper.nativeElement.clientWidth - 36;
}