要在页面加载时获取元素的宽度,可以使用Angular的ViewChild和ElementRef来实现。以下是一个示例代码:
在HTML模板中,添加一个带有引用变量的元素:
示例元素
在组件的代码中,使用ViewChild和ElementRef来获取元素的宽度:
import { Component, AfterViewInit, ViewChild, ElementRef } from '@angular/core';
@Component({
selector: 'app-my-component',
templateUrl: './my-component.component.html',
styleUrls: ['./my-component.component.css']
})
export class MyComponentComponent implements AfterViewInit {
@ViewChild('myElement', {static: false}) myElement: ElementRef;
ngAfterViewInit() {
const elementWidth = this.myElement.nativeElement.offsetWidth;
console.log('元素宽度:', elementWidth);
}
}
在上面的代码中,@ViewChild('myElement')装饰器将元素的引用绑定到myElement属性上。然后,在ngAfterViewInit生命周期钩子中,可以使用nativeElement来访问原生的DOM元素,并使用offsetWidth属性获取元素的宽度。
请注意,由于ngAfterViewInit在Angular检测变更之后调用,因此元素的宽度将在页面加载后立即可用。
这是一种使用Angular和SVG来获取元素宽度的解决方法。