Мне удалось заставить мое приложение Angular (8) реагировать на нажатие загруженного изображения SVG.
Мне не нравится мое решение, поскольку код компонента Angular знает о внутренностях файла SVG, а также делает некоторые манипуляции с DOM.
Есть ли способ избавиться от addEventListener
и getElementById
?
Код компонента:
@Component({ ... })
export class StartPageComponent {
@ViewChild('startimage', {static:false})
private startimage: ElementRef;
ngAfterViewInit() {
const svg = this.startImage.nativeElement.getSVGDocument();
// We have to wait until the image is loaded to have its elements populated.
this.startImage.nativeElement.addEventListener('load', () => {
const button1 = svg.getElementById('g-element1');
button1.addEventListener('click', () => {
// With this solution the whole page blinks.
// It would be nicer to have it just do a regular Angular route.
window.location.href = '/somepage;
});
const button2 = svg.getElementById('g-element2');
button2.addEventListener('click', () => {
..
});
});
}
}
Файл html:
<embed #startimage id="startimage" src="/assets/startimage.svg" type="image/svg+xml"/>
Файл SVG:
<svg xmlns="http://www.w3.org/2000/svg">
...
<g id="g-element1">
...
</g>
<g id="g-element2">
...
</g>
...
</svg>