[英]Angular 4 using setter on @ViewChild
我在這里有一個演示
我試圖在使用* ngIf將元素添加到DOM后獲取元素的高度
我試圖通過在@ViewChild上使用setter來實現這一點,應該調用setter,* ngIf變為true。
在我的例子中,它似乎只在添加元素然后刪除(按鈕被點擊兩次)時才起作用。
當元素顯示時,我怎樣才能使它工作。
我知道我可以用[hidden]而不是* ngIf來做這個,但是我的實際代碼有很多元素,我不想立刻放在DOM中
import { Component, Input, ElementRef, ViewChild } from '@angular/core';
@Component({
selector: 'child-comp',
templateUrl: './child.component.html'
})
export class ChildComponent{
@Input() parent: ElementRef;
private blockThree: ElementRef;
@ViewChild('blockThree') set content(content: ElementRef) {
this.blockThree = content;
}
showThree: boolean = false
blockHeightThree: number
constructor(){ }
showBlockThree(){
this.showThree = !this.showThree
this.blockHeightThree = this.blockThree.nativeElement.clientHeight;
console.log('element height '+this.blockHeightThree);
}
}
它只能第二次工作的原因是, this.showThree = !this.showThree
不會立即調用setter,因為整個函數首先完成,然后angular實際檢測到更改並將元素放置到位。 如果將高度讀取邏輯移動到設置器中,它將起作用。
這意味着你無法在showBlockThree
函數中讀取blockHeightThree
,因為塊3還沒有。 但是有一個不優雅的解決方案。 你可以在那里放置setTimeout()
,以便異步讀取高度。 也許它會做你需要的。
@ViewChild('blockThree') set content(content: ElementRef) {
console.log("block three", content)
this.blockThree = content;
if (this.blockThree) {
this.blockHeightThree = this.blockThree.nativeElement.clientHeight;
console.log(this.blockThree.nativeElement.clientHeight);
}
}
showBlockThree() {
this.showThree = !this.showThree
console.log('element height ' + this.blockHeightThree);
setTimeout(()=> console.log("async block three", this.blockHeightThree));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.