我不明白为什么在一个
ViewChild
中去掉#
,因为您不需要它:@ViewChild('refId') textDiv:ElementRef;
其次,ViewChild
变量在AfterViewInit
生命周期之前不会被初始化,所以你需要将你的代码从ngOnInit
移动到ngAfterViewInit
中:
ngAfterViewInit() {
if(Globals.refLineCounter == null) {
Globals.refLineCounter = this;
//console.log(Globals.refLineCounter.getHeight());
console.log(this.getHeight());
}
}
ngAfterViewInit
事件触发后,可以引用ViewChild(en)。您需要从@angular/core
实现接口AfterViewInit
。@ViewChild
属性中不使用哈希符号引用它,则需要使用CSS选择器或在模板中提供的名称。有关其他生命周期钩子详细信息,请参见https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html。
这里只列出了您代码中必要的部分(我删除了OnInit
,因为在此组件中似乎不再需要)。
import {Component, Input, ElementRef, ViewChild, AfterViewInit} from '@angular/core';
export class LineCounterComponent implements AfterViewInit {
@ViewChild('refId') textDiv:ElementRef;
ngAfterViewInit() {
if(Globals.refLineCounter == null) {
Globals.refLineCounter = this;
//console.log(Globals.refLineCounter.getHeight());
console.log(this.getHeight());
}
}
}