首页 > 解决方案 > 在 nativeElement 从角度 8 升级到 9 时,角度是否有重大变化

问题描述

我最近将我的 angular cli 版本从早期版本的 8 升级到了 9.1.4。所以我想问一下这个 nativeElement 的东西是否有重大变化。

我使用 nativeElement 的 ts 文件的一些代码如下

import { Component, OnInit, ViewChild, ElementRef, Renderer2, Input } from '@angular/core';

@Component({
  selector: 'app-note-card',
  templateUrl: './note-card.component.html',
  styleUrls: ['./note-card.component.scss']
})
export class NoteCardComponent implements OnInit {

  @Input() title: string;
  @Input() body: string;

  @ViewChild('truncator') truncator: ElementRef<HTMLElement>;
  @ViewChild('bodyText') bodyText:ElementRef<HTMLElement>;

  constructor(private renderer: Renderer2) { }



ngOnInit() {

    // work out if there is a text overflow and if not then hide the truncator

    let style = window.getComputedStyle(this.bodyText.nativeElement, null);
    let viewableHeight = parseInt(style.getPropertyValue("height"), 10);

    if(this.bodyText.nativeElement.scrollHeight>viewableHeight){
      // if there is a text overflow, show the fade out truncator
      this.renderer.setStyle(this.truncator.nativeElement, 'display', 'block');
    }else{
      // else (there is a text overflow), hide the fade out truncator
      this.renderer.setStyle(this.truncator.nativeElement, 'display', 'none');
    }
  }

}

这是我在浏览器中遇到的错误

ERROR TypeError: Cannot read property 'nativeElement' of undefined
    at NoteCardComponent.ngOnInit (note-card.component.ts:22)
    at callHook (core.js:4735)
    at callHooks (core.js:4699)
    at executeInitAndCheckHooks (core.js:4639)
    at selectIndexInternal (core.js:9701)
    at Module.ɵɵadvance (core.js:9662)
    at NotesListComponent_Template (notes-list.component.html:19)
    at executeTemplate (core.js:12098)
    at refreshView (core.js:11945)
    at refreshComponent (core.js:13410)
defaultErrorLogger @ core.js:6237

欢迎任何帮助提前谢谢:)

标签: javascriptangulartypescript

解决方案


@ViewChild()装饰器使查询的元素仅从开始可用AfterViewInit。因此,不要在ngOnInit方法中运行代码,而是将其移动到ngAfterViewInit方法中。


推荐阅读