[英]How can I add more SVG or Html elements / events to <ngx-graph> template with Angular 5?
[英]How to control SVG template (click events) in Angular
In an Angular project I have an SVG map of a country, with all of its regions, and I'm trying to put this SVG map as a template of a component.
因此,在 SVG 文件中,我将每个区域表示为<path>
或<polygon
元素,总共超过 70 个区域。 其中一个要求是以某种颜色突出显示每个单击的区域。
除了在所有 70 个<path>
和<polygon
元素上添加(click)
事件之外,有没有办法处理每个区域( <path>
和<polygon
元素)上的点击事件,因为这对我来说似乎很多代码重复
注意:这里我不能在 SVG 元素上使用循环。
我已经在每个 svg 元素上添加了一个点击事件。 当然你不应该自己做,但你可以在你的 dom 元素中以编程方式导航并自动添加点击事件。
我不知道您的代码如何,但这里有一个示例:
<svg #mySvg></svg>
在 component.ts 中也许这样的东西应该起作用:
@ViewChild('mySvg') mySvg: SVGElement;
// other code
const children = this.mySvg.children;
for (var i = 0; i < children.length; i++) {
const childElement = children[i];
childElement.addEventListener('click', function (e) {
// Do stuff
});
}
根据您的用例使用ViewChild
或ViewChildren
。
这有点伪代码,但它应该可以帮助您入门。
@Component({
...
template: `<svg #map>...<svg>`
})
export class MapComponent implements AfterViewInit {
@ViewChild('map') map: HTMLElement // or SvgHTMLElement counterpart
@HostListener('click')
onMapComponentClicked(event: MouseEvent) {
const clickedElement = this.getClickedSvg(event)
if(!clickedElement) return
// Do something with the clicked SVG; maybe read it's ID
}
private getClickedSvg(event: MouseEvent): HTMLElement? {
return (
Array.from(this.map.children).find(el => el.contains(event.target))
)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.