2016-12-18 107 views
3

我不明白爲什麼ViewChild被返回null時完全相同的代碼工作的textarea元素,但它不會在div角2 ViewChild不起作用

模板工作:

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

組件:在你的代碼

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

回答

7

兩個錯誤 - 首先從ViewChild刪除#,你不需要它:

@ViewChild('refId') textDiv:ElementRef; 

其次,ViewChild變量不前AfterViewInit生命週期初始化,所以你需要在你的代碼擺脫ngOnInitngAfterViewInit

ngAfterViewInit() { 
    if(Globals.refLineCounter == null) { 
     Globals.refLineCounter = this; 
     //console.log(Globals.refLineCounter.getHeight()); 
     console.log(this.getHeight()); 
    } 
} 
0
  • ViewChild(EN)可以在ngAfterViewInit事件之後被引用火災。您需要實現從@angular/core的接口AfterViewInit
  • 您需要使用CSS選擇器,或者如果您使用散列符號但是在@ViewChild屬性中沒有散列,則可以使用您在模板中提供的名稱。

另請參閱https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html瞭解更多生命週期鉤子的詳細信息。

這裏只是你的代碼中必需的(我刪除了OnInit,因爲它在這個組件中似乎不再需要)。

​​