Angular 2的ViewChild无法正常工作

4
我不明白为什么在一个
2个回答

7
您的代码中有两个错误 - 首先需要从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());
    }
}

0
  • 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());
      }
    }   
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接