在Angular指令中找到新创建的元素的高度和宽度可以通过以下步骤实现:
@ViewChild
装饰器获取对新创建元素的引用。例如,如果指令的选择器为myDirective
,可以在指令类中添加以下代码:@ViewChild('newElement') newElement: ElementRef;这里假设新创建的元素有一个模板引用变量为newElement
。ngAfterViewInit
生命周期钩子函数中,可以通过nativeElement
属性访问到新创建元素的DOM对象,并获取其高度和宽度。例如:ngAfterViewInit() {
const height = this.newElement.nativeElement.offsetHeight;
const width = this.newElement.nativeElement.offsetWidth;
console.log('Height:', height);
console.log('Width:', width);
}这里使用offsetHeight
和offsetWidth
属性获取元素的高度和宽度。elementSize
属性显示元素的高度和宽度:<div #newElement myDirective>
<p>Element Height: {{ elementSize?.height }}</p>
<p>Element Width: {{ elementSize?.width }}</p>
</div>总结:
通过使用@ViewChild
装饰器获取新创建元素的引用,并在ngAfterViewInit
生命周期钩子函数中访问其高度和宽度,可以在Angular指令中找到新创建的元素的尺寸。
领取专属 10元无门槛券
手把手带您无忧上云