[英]Is there a breaking change in angular when upgrading from angular 8 to 9 in nativeElement
我最近将我的 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
欢迎任何帮助提前谢谢:)
当您在OnInit
生命周期挂钩中使用ViewChild
装饰器时,您必须将static
属性指定为 true 以在更改检测运行之前解析查询结果。 默认情况下为false
,因此它会在更改检测运行后解决。
要在ngOnInit
中使用,就像您的情况一样,请参见下面的代码:
@ViewChild('truncator', { static: true }) truncator: ElementRef<HTMLElement>;
@ViewChild('bodyText', { static: true }) bodyText:ElementRef<HTMLElement>;
如果您不在OnInit
中使用,则需要将其设置为 false。 在 Angular 中,在这种情况下 9 是可选的,因为默认值为 false。
我想知道,你怎么没有得到 Angular 8 中的错误,在这两种情况下这个属性都是强制性的。
@ViewChild()
装饰器使查询的元素仅在AfterViewInit
上可用。 因此,不要在ngOnInit
方法中运行代码,而是将其移至ngAfterViewInit
方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.