angular 2 ViewChild不起作用
发布时间:2020-12-17 17:22:41 所属栏目:安全 来源:网络整理
导读:我无法理解为什么当相同的确切代码在textarea元素上工作时ViewChild返回null,但它不适用于div 模板: div #refId class = 'line_counter' {{lineNumber}}/div 零件: import {Component,OnInit,Input,ElementRef,ViewChild} from '@angular/core';import {Gl
我无法理解为什么当相同的确切代码在textarea元素上工作时ViewChild返回null,但它不适用于div
模板: <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; } } 解决方法
代码中的两个错误 – 首先从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()); } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |