javascript - 在 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
欢迎任何帮助提前谢谢:)
解决方案
@ViewChild()
装饰器使查询的元素仅从开始可用AfterViewInit
。因此,不要在ngOnInit
方法中运行代码,而是将其移动到ngAfterViewInit
方法中。
推荐阅读
- django - 提高 Django ORM 中的性能
- javascript - 循环比较字母的问题
- react-native - react-native zoom-bridge sdk在ios真实设备中构建不工作,但在模拟器中,它正在工作
- r - 如何通过 R 中的值(不加入)匹配两个 dfs?
- python - 将对象放置在pygame中的随机位置
- unix - 将文件从 Openshift 复制到外部 unix 机器
- flutter - 带有文本 + 图标的按钮,在使用 Flutter 滚动时仅变为图标
- python - 为什么在使用 Numpy 追加列与行时我们对括号的使用不同?
- python - Python中的网络爬虫
- jenkins - 在后期检查每个阶段的结果 - Jenkins Pipeline