gpt4 book ai didi

angular - 如何通过 Angular ViewChildren 访问 SVG 元素

转载 作者:搜寻专家 更新时间:2023-10-30 21:34:22 28 4
gpt4 key购买 nike

我有一个 svg 作为对象加载:

<object data="assets/img/states.svg" type="image/svg+xml" id="map"></object>

这个 svg 包含一个大的 png map 和几个矩形和文本元素。

<rect
y="224.72084"
x="644.87109"
height="231.68137"
width="101.08391"
id="RECT_TO_GET" />

我想获取数组中的所有 rect 元素,就像我处理普通的 html 元素一样:

@ViewChildren('rect') rects !: QueryList<any>;
this.rects.forEach(r=> {
console.log(r);
});

问题是 rects 数组总是空的。我试图在 ngViewAfterInit()ngAfterViewChecked() 中获取它们,但没有成功。我怎样才能到达 svg 的元素?

我还没有尝试通过 getElementsById() 获取它们,如果可能的话,我想以 Angular 方式来获取它们。

整个事情就是在我获得每个矩形元素后为其提供上下文颜色。

最佳答案

ViewChildViewChildren 不支持 CSS 选择器

https://angular.io/api/core/ViewChild

Supported selectors include:

  • any class with the @Component or @Directive decorator
  • a template reference variable as a string (e.g. query with@ViewChild('cmp')`)
  • any provider defined in the child component tree of the current component (e.g. @ViewChild(SomeService) someService: SomeService)
  • any provider defined through a string token (e.g. @ViewChild('someToken') someTokenVal: any)
  • a TemplateRef (e.g. query with @ViewChild(TemplateRef) template;)

您可以从模板引用变量中获取 HtmlElement 并在加载对象元素资源后开始尝试操作它

online example

html

  <object #mySvg data="./assets/new.svg" type="image/svg+xml" id="map"></object> 

组件

  @ViewChild('mySvg') mySvg;

ngOnInit() {
const objElm = (this.mySvg.nativeElement as HTMLObjectElement);
objElm.onload = () => {
const paths = objElm.contentDocument.querySelectorAll('path');

paths.forEach((path,index) => {
console.log(`path:${index} , d=${path.getAttribute("d")}`);
})

}
}

关于angular - 如何通过 Angular ViewChildren 访问 SVG 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54040857/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com