user1257255
user1257255

Reputation: 1171

Angular 4 using Renderer2/HostListener for clicked outside event

I have developed a component consisting of basic input field and a suggestions dropdown list which is shown when user clicks into input (similar to ng-select). However, when user wants to close dropdown list can either unfocus it with tab/shift-tab/esc/... or it can click somewhere outside the whole component. When developing for browser platform in Angular 4, this is quite simple with HostListener, ElementRef and nativeElement. My current solution for browser platform is (also seen in other SO question):

@HostListener('document:click', ['$event'])
onClickedOutside(event: any): void {
  if (!this.elementRef.nativeElement.contains(event.target)) {
    this.hideDropdown();
  }
}

Since Angular aim is to be platform indpendent, I want to standardize this component to be compatible with webworker platform (along browser platform), because I'd like to use it in my project (idea is to transfer some calculation logic to client-side, to minimize workload on server and still have responsive UI). I already tried to replace ... nativeElement.contains ... with some other method which would perform check, but unfortunately when this event is being triggered under webworker platform, $event has only some basic info about mouse position, without actual target which is clicked (I think properties of DomRenderer class are shown).

I'm not really well informed with the current state of webworker platform and if it's ready for such things, so I'm looking for the solution or workaround on how to track outside click. If this is somehow not possible, I would please you to at least describe why my idea cannot be implemented or how would you do it (for example stay on browser platform and use webworker platform when this will be supported). Thank you in advance!

Upvotes: 1

Views: 1130

Answers (1)

Amy Doxy
Amy Doxy

Reputation: 739

Angular 4 provides a constant DOCUMENT in @angular/platform-browser package which you can use with injection in the constructor of your component

import { Inject } from "@angular/core";
import { DOCUMENT } from "@angular/platform-browser";

export class DumpComponent implements OnInit {
 constructor(@Inject(DOCUMENT) private document: Document) { }
}

Upvotes: 0

Related Questions