Nesting NgIf and (click) in Angular2

I have got a button which when clicked produces a number of child elements, I want to create a “collapse if the user clicks anywhere other than one of the child buttons” effect. To do this, I want to attach a (click) = xyz() to the whole page, but only have that active if the button has been expanded. Then I would position the child elements infront of the page wide selector (with css z-index). Is it possible to achieve that, or is there a better way of doing that?

Here is what I have so far (only toggles from the button click).

enter image description here

2
Leave a Reply

avatar
2 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
Jason Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
Jason
Guest

You can still use the declarative approach and just ignore events while collapsed

@HostListener('window:click', ['$event'])
windowClickHandler(event) {
  if(!this.expanded) return;
  collapse();
}

another way could be a directive that is only enabled when expanded

@Directive({
  selector: 'globalClick'
  host: {
      '[style.display]':'"none"',
  }
}
class GlobalClick {
  @Output() globalClick:EventEmitter = new EventEmitter();

  @HostListener('window:click', ['$event'])
  windowClickHandler(event) {
    this.globalClick.emit(event);
  }
}

and then use it like

<span *ngIf="expanded" (globalClick)="collapse($event)">

Jason
Guest

I’m using window object directly,but is not recommended:

//save reference
this.listener = (event)=>{...};

window.addEventListener('click', this.listener);
window.removeEventListener('click', this.listener);