Apply style to element when click outside of directive attribute element in Angular

Viewed 59

I have svg items that highlights their corresponding path when user click on them or hover them.

I'm using Directives to detect onEnter onLeave and Click events.

Its working fine when I hover ( I highlight ) then when I leave the element (I Play down )

Then When I click also the path is highlighted (

Actually what's happen is when I click elsewhere the Highlight stays.

What I can't do so is when I click on the rest of the screen I would like that the Highlight disappear.

Here's my directive logic

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 part 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>

Here's an example on stackBlitz

1 Answers
document.removeEventListener('mousedown', this.scroll);

What I have used is that whenever mousedown event fires removeListner remove scroll event. Which we added before using addEventListner() . this.scroll is your defined event to do what you want to do.

Related