Issue
I have an svg loaded as an object:
<object data="assets/img/states.svg" type="image/svg+xml" id="map"></object>
This svg contains a big png map and several rect and text elements.
<rect
y="224.72084"
x="644.87109"
height="231.68137"
width="101.08391"
id="RECT_TO_GET" />
I'd like to get all the rect
elements in an array just like I do with normal html elements like this:
@ViewChildren('rect') rects !: QueryList<any>;
this.rects.forEach(r=> {
console.log(r);
});
The problem is that the rects array is always empty. I have tried to get them in ngViewAfterInit()
and in ngAfterViewChecked()
without success. How can I reach the elements of an svg?
I haven't tried to get them by getElementsById()
yet, I'd like to do it the angular way if it's possible.
The whole thing is just about giving contextual colors of each rect elements once I get them.
Solution
ViewChild
or ViewChildren
cannot support CSS selectors
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;)
you can get the HtmlElement from a template reference variable and start trying to manipulate it after Object Element Resource Loaded
html
<object #mySvg data="./assets/new.svg" type="image/svg+xml" id="map"></object>
component
@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")}`);
})
}
}
Answered By - Chunbin Li
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.