gpt4 book ai didi

Angular 2 ViewChild 不工作

转载 作者:太空狗 更新时间:2023-10-29 17:46:43 25 4
gpt4 key购买 nike

我不明白为什么当相同的代码在 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());
}
}

关于 Angular 2 ViewChild 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41212064/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com