I
I
Ivan Stroykin2017-07-03 15:16:10
Angular
Ivan Stroykin, 2017-07-03 15:16:10

HostListener document:click on one component among many copies?

Good day,
There is a component that displays a string, when clicked, a form pops up for editing this string.
This component is used in tables, that is, in one table ~ 50 copies of this component.
Well, you need to make sure that when you click outside the component area, the component closes.
I write like this:

...
@HostListener('document:keyup', ['$event'])
public handleClick(event) {
  if (!this.editable.nativeElement.contains(event.target)) this.onClose();
}

But when opening and then clicking outside the component area, this method fires all 50 times (how many components are on the page). Because of this, everything slows down a bit (closing pause for 1.5 seconds)
Can I somehow distinguish between the components? To make this method work only for a public component?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Zuev, 2017-07-03
@StivinKing

You can assign closure handling to a special directive, which might look like

@Directive({
    selector: '[outsideClickHandler]',
})
export class OutsideClickDirective {
    @Output('outsideClickHandler') close = new EventEmitter();

    isOpen: boolean = false;

    constructor(private elRef: ElementRef) {}

    @HostListener('document:click', ['$event'])
    public handleClick(event) {
      if (!this.isOpen)  {
          this.isOpen = true;
      } else if (!this.elRef.nativeElement.contains(event.target)) {
          this.close.emit();
      }
    }
}

then easily use it in your template
Live example

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question