[英]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.