Javascript viewChild在控制台中显示未定义
//这是我的html文件,我在这里声明了“#bodyText”和#truncated以访问组件中的元素,但在onInit()hook中显示了未定义的,但是在ngAfterView()组件中工作正常Javascript viewChild在控制台中显示未定义,javascript,html,angular,Javascript,Html,Angular,//这是我的html文件,我在这里声明了“#bodyText”和#truncated以访问组件中的元素,但在onInit()hook中显示了未定义的,但是在ngAfterView()组件中工作正常 <div class="note-card-content"> <h1 class="note-card-title">{{title}}</h1> <div #bodyText class=&quo
<div class="note-card-content">
<h1 class="note-card-title">{{title}}</h1>
<div #bodyText class="note-card-body">
<p>{{body}}</p>
<div #truncator class="fade-out-truncation"></div>
</div>
</div>
<div class="x-button"></div>
{{title}}
{{body}}
//这是组件
从'@angular/core'导入{Component,ElementRef,Input,OnInit,Renderer2,ViewChild};
@组成部分({
选择器:“应用程序注释卡”,
templateUrl:'./note card.component.html',
StyleURL:['./注意card.component.scss']
})
导出类NoteCardComponent实现OnInit{
//当我在控制台上打印时,这两个元素显示为未定义
@ViewChild('truncator')truncator:ElementRef;
@ViewChild('bodyText')bodyText:ElementRef;
@输入()标题:字符串;
@Input()主体:字符串
构造函数(私有呈现器:Renderer2){}
ngOnInit():void{
console.log(this.truncator)
//确定是否存在文本溢出,如果是,则隐藏
让style=window.getComputedStyle(this.bodyText.nativeElement,null);
让viewableHeight=parseInt(style.getPropertyValue(“高度”),10)
if(this.bodyText.nativeElement.scrollHeight>viewableHeight){
//如果没有文本溢出,则显示淡出截断符
this.renderer.setStyle(this.truncator.nativeElement、'display'、'block')
}否则{
//else(存在文本溢出)
this.renderer.setStyle(this.truncator.nativeElement,'display','none')
}
}
}
有什么问题吗?:)
这是正常的行为
ngOnInit(){}
在Angular初始化组件视图和子视图之前运行。你不应该为了这个目的使用ngOnInit。我建议您看看。因为您的HTML还没有加载,如果您阅读lifecycle挂钩,您就会知道ngAfterViewInit是在Angular完全初始化组件的视图之后调用的,而ngOnInit是在这之前调用的。所以只需将处理移到NgafterViewInEntity中,问题是?如果您使用选项static:false
声明@ViewChild
属性,则只有在ngAfterViewInit()钩子中以ergo方式呈现属性后,才能访问它们。
import { Component, ElementRef, Input, OnInit, Renderer2, ViewChild } from '@angular/core';
@Component({
selector: 'app-note-card',
templateUrl: './note-card.component.html',
styleUrls: ['./note-card.component.scss']
})
export class NoteCardComponent implements OnInit {
//These two elements are showing undefined when I print on console
@ViewChild('truncator') truncator:ElementRef<HTMLElement>;
@ViewChild('bodyText') bodyText:ElementRef<HTMLElement>;
@Input() title:string;
@Input() body:string
constructor(private renderer:Renderer2) { }
ngOnInit(): void {
console.log(this.truncator)
// Work out if there is a text overflow and if so,then hide
let style = window.getComputedStyle(this.bodyText.nativeElement,null);
let viewableHeight = parseInt(style.getPropertyValue("height"),10)
if(this.bodyText.nativeElement.scrollHeight > viewableHeight){
// if there is no text overflow ,show the fade out truncator
this.renderer.setStyle(this.truncator.nativeElement,'display','block')
}else{
// else (there is a text overflow)
this.renderer.setStyle(this.truncator.nativeElement,'display','none')
}
}
}