Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular 2 ViewChild doesnt work

I can't understand why ViewChild is returning null when the same exact code works on a textarea element, but it won't work on div

Template:

<div #refId class = 'line_counter' >
    {{lineNumber}}
</div>

Component:

import {Component, OnInit, Input, ElementRef, ViewChild} from '@angular/core';
import {Globals} from "../../../globals";

@Component({
  selector: 'app-line-counter',
  templateUrl: './line-counter.component.html',
  styleUrls: ['./line-counter.component.css']
})
export class LineCounterComponent implements OnInit {

  @ViewChild('#refId') textDiv:ElementRef;

  @Input() lineNumber : number = 0;

  constructor() {
  }

  ngOnInit() {
    if(Globals.refLineCounter == null) {
      Globals.refLineCounter = this;
      //console.log(Globals.refLineCounter.getHeight());
      console.log(this.getHeight());
    }
  }

  getHeight(){
    return this.textDiv.nativeElement.height;
  }
}
like image 979
dvrer Avatar asked Mar 10 '23 09:03

dvrer


1 Answers

Two mistakes in your code - first remove # from ViewChild, you don't need it:

@ViewChild('refId') textDiv:ElementRef;

Second, ViewChild variables are not initialised before AfterViewInit lifecycle, so you need to move your code from ngOnInit to ngAfterViewInit:

ngAfterViewInit() {
    if(Globals.refLineCounter == null) {
      Globals.refLineCounter = this;
      //console.log(Globals.refLineCounter.getHeight());
      console.log(this.getHeight());
    }
}
like image 99
Stefan Svrkota Avatar answered Mar 21 '23 06:03

Stefan Svrkota