dvr*_*rer 4 typescript angular2-template angular
我无法理解为什么ViewChild当相同的确切代码在textarea元素上工作时返回null ,但它不起作用div
模板:
<div #refId class = 'line_counter' >
{{lineNumber}}
</div>
Run Code Online (Sandbox Code Playgroud)
零件:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
代码中的两个错误 - 首先#从中移除ViewChild,您不需要它:
@ViewChild('refId') textDiv:ElementRef;
Run Code Online (Sandbox Code Playgroud)
其次,ViewChild变量在AfterViewInit生命周期之前没有初始化,因此您需要将代码从以下位置移动ngOnInit到ngAfterViewInit:
ngAfterViewInit() {
if(Globals.refLineCounter == null) {
Globals.refLineCounter = this;
//console.log(Globals.refLineCounter.getHeight());
console.log(this.getHeight());
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2878 次 |
| 最近记录: |