簡體   English   中英

viewChild 在控制台中顯示未定義

[英]viewChild is showing undefined in console

//這是我的 html 文件,這里我聲明了“ #bodyText ”和#truncated以訪問組件中的元素,但在 onInit() 鈎子中顯示未定義,但是它在ngAfterView () 組件中工作正常。

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

// 這是組件

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') } } }

有什么問題? :) 這是正常行為。 ngOnInit(){}在 Angular 初始化組件的視圖和子視圖之前運行。 您不應該為此目的使用 ngOnInit。 我建議你看看Lifecycle hooks, Angular

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM