[英]Can't add element to DOM
在組件中,我有一些代碼片段
isLoaded($event) {
console.log($event);
this.visible = $event;
console.log(this.visible);
this.onClick();
}
onClick() {
this.listImage = this.imageService.getImage();
let span = document.createElement('span');
span.innerHTML = ['<img class="thumb" src="', this.listImage[0],
'" title="', '"/>'
].join('');
document.getElementById('previewImg').insertBefore(span, null);
}
在HTML代碼中我有
<div *ngIf="visible">
<div id='previewImg' class="img_content"></div>
$ event返回true <=> visible = true,但是我有錯誤
Cannot read property 'insertBefore' of null
沒有* ng如果網站渲染正常。
為什么會這樣呢?
根據我的評論,您的問題是由於爭用條件引起的 :當visible
屬性解析為真實值時, ngIf
指令將導致嵌套的DOM節點呈現。 但是,當this.onClick()
時,此渲染未完成,這意味着in中的DOM節點在查詢時將返回null
。
換句話說,您的document.getElementById('previewImg')
將返回null
,這是錯誤的根源。
為了避免這種情況,您必須確保選擇器在調用堆棧的末尾執行:這可以簡單地通過使用window.setTimeout(fn, 0)
來完成,例如:
onClick() {
// Other logic can happen since they do not depend on the updated DOM
this.listImage = this.imageService.getImage();
let span = document.createElement('span');
span.innerHTML = ['<img class="thumb" src="', this.listImage[0],'" title="', '"/>'].join('');
// Query at end of callstack
window.setTimeout(function() {
document.getElementById('previewImg').insertBefore(span, null);
}, 0);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.