I've implemented SVG items that highlight their corresponding path when a user clicks or hovers over them.
To achieve this, I am utilizing Directives to detect events such as onEnter
, onLeave
, and Click
.
The highlighting works smoothly when I hover over the element (it highlights), and it also stays highlighted when I click on it.
However, the issue arises when I click elsewhere and the highlight remains.
What I aim to do is make the highlight disappear when I click on any other part of the screen.
Below is the logic for my directive:
export class HighlightDirective {
constructor(private renderer: Renderer2, private el: ElementRef) {}
clicked = false;
@HostListener('mouseenter') onMouseEnter() {
this.changeOpacity(1);
}
@HostListener('mouseleave') onMouseLeave() {
if (!this.clicked) {
this.changeOpacity(0);
}
}
@HostListener('click') click() {
this.changeOpacity(1);
this.clicked = true;
}
changeOpacity(opacity: number) {
this.renderer.setStyle(this.el.nativeElement.nextSibling, 'opacity', opacity);
}
}
And here's a snippet of the SVG with the Highlight attribute tag:
<g id="b1" transform="translate(-885 -562)">
<g id="b1select">
<ellipse id="Ellipse_1" data-name="Ellipse 1" cx="5.3" cy="5.3" rx="5.3" ry="5.3" transform="translate(1309.17 932.12)" fill="none" stroke="#b18802" stroke-width="1"/>
<text id="B1-2" data-name="B1" transform="translate(1310.67 939.62)" fill="#b18802" font-size="6" font-family="ArialMT, Arial"><tspan x="0" y="0">B1</tspan></text>
</g>
<rect appHighlight (click)="openDialog($event)" id="container" width="12" height="11" transform="translate(1308.67 931.62)" fill="rgba(255,255,255,0)"/>
<path id="b1-3" data-name="b1" d="M1093.763,1595.658v-82.417s5-14.987-18.452-16.644-40.9,2.386-54.093-11.537-132.873-159.193-132.873-159.193-6.456-10.249-24.986-14.661-9.858-17.907-4.728-25.235,39.039-47.23,39.039-47.23" transform="translate(208.67 -656.38)" fill="none" stroke="#efcf2f" stroke-linecap="round" stroke-width="2"/>
</g>
Check out an example on StackBlitz.