简体   繁体   中英

ElementRef is undefined when using @ViewChild

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

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM