0

I am creating a Angular directive, please help me how can detect each event for 'click' elements and 'click' outside elements in Angular(7).

@Hostlistener ('click', ['$event']) onClick(){}

for clicking elements(button here)

@Hostlistener ('document:click', ['$event'] outClick(){}

for click anyway in the document. But this also indicate the elements.

Already one click event for elements existed when click the outside elements, only recognize that it's not elements.

msanford
  • 11,803
  • 11
  • 66
  • 93

1 Answers1

1

Inside of your click event logic, you can check to see if the click position is within the element. Try something like this:

@ViewChild('elementName') element: ElementRef;

@Hostlistener ('click', ['$event']) onClick(e: MouseEvent) {
  if (this.element.nativeElement.contains(e.target)) {
    // Logic for click inside
  } else {
    // Logic for click outside
  }
}

where elementName is the name of the reference variable for an element in your component template using the # syntax. The ViewChild decorator binds a property to the element in your template so that you can check the click target against it in your event handler function. For example of how to name the element in your template:

<button #elementName>Click Me</button>
John
  • 2,395
  • 15
  • 21