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;
}
}
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());
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With