在Angular中获取一个区域下的所有SVG对象,可以通过以下步骤实现:
以下是在Angular中获取特定区域下所有SVG对象的示例代码:
<div id="svg-container">
<svg width="100" height="100" id="svg1">
<circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" />
</svg>
<svg width="100" height="100" id="svg2">
<rect width="100" height="100" style="fill:blue;stroke-width:3;stroke:rgb(0,0,0)" />
</svg>
</div>
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-svg-fetcher',
templateUrl: './svg-fetcher.component.html',
styleUrls: ['./svg-fetcher.component.css']
})
export class SvgFetcherComponent implements OnInit {
constructor() { }
ngOnInit(): void {
this.fetchSvgs();
}
fetchSvgs(): void {
const container = document.getElementById('svg-container');
if (container) {
const svgs = container.getElementsByTagName('svg');
for (let i = 0; i < svgs.length; i++) {
console.log(svgs[i]); // 这里可以对每个SVG元素进行操作
}
}
}
}
问题: 如果页面上的SVG元素是动态生成的,上述方法可能无法获取到这些元素。 解决方法: 使用Angular的变更检测机制或RxJS来监听DOM变化,确保在SVG元素添加到DOM后执行获取操作。
import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
import { fromEvent } from 'rxjs';
import { debounceTime, distinctUntilChanged, map } from 'rxjs/operators';
@Component({
selector: 'app-svg-fetcher',
templateUrl: './svg-fetcher.component.html',
styleUrls: ['./svg-fetcher.component.css']
})
export class SvgFetcherComponent implements OnInit {
@ViewChild('svgContainer') svgContainer: ElementRef;
constructor() { }
ngOnInit(): void {
this.observeChanges();
}
observeChanges(): void {
fromEvent(this.svgContainer.nativeElement, 'DOMSubtreeModified')
.pipe(
debounceTime(100),
distinctUntilChanged(),
map(() => this.svgContainer.nativeElement.getElementsByTagName('svg'))
)
.subscribe(svgs => {
for (let i = 0; i < svgs.length; i++) {
console.log(svgs[i]);
}
});
}
}
通过这种方式,可以确保即使SVG元素是动态添加的,也能正确地获取到它们。
领取专属 10元无门槛券
手把手带您无忧上云