在Angular 10中,使用SVG元素的getBBox()方法可能返回错误的值。一个解决方法是使用ViewChild装饰器来引用SVG元素,并在ngAfterViewInit生命周期钩子中调用getBBox()方法。
首先,在组件的模板文件中,给SVG元素一个模板引用变量:
然后,在组件的类文件中,使用ViewChild装饰器引用SVG元素,并在ngAfterViewInit生命周期钩子中调用getBBox()方法:
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 MyComponent implements AfterViewInit {
@ViewChild('mySvg', { static: false }) mySvg: ElementRef;
ngAfterViewInit() {
const svgElement = this.mySvg.nativeElement as SVGSVGElement;
const bbox = svgElement.getBBox();
console.log('BBox:', bbox);
}
}
这样,你就可以在控制台中看到正确的BBox值了。请确保在ngAfterViewInit生命周期钩子中调用getBBox()方法,以确保元素已经被正确地初始化。
希望这个解决方法对你有帮助!