我有一个演示here https://stackblitz.com/edit/angular-dgmnlf?file=app%2Fchild.component.ts
我正在尝试使用 *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 才真正检测到更改并将元素放置到位。如果您将高度读取逻辑移至设置器中,它将起作用。
这意味着你无法阅读blockHeightThree
in the showBlockThree
函数,因为第三块还不存在。但有一个不优雅的解决方案。你可以把setTimeout()
在那里,高度是异步读取的。也许它会满足你的需要。
工作演示 https://stackblitz.com/edit/angular-7qw9q5?file=app/child.component.ts
@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));
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)