Conditionally apply click event in Angular 4

There is no way to enable/disable bindings.

It's possible to do that imperatively

@ViewChild('.user') aUser:ElementRef; 

clickHandler(event) {
  console.log(event);
}
_clickHandler = this.clickHandler.bind(this);

ngAfterViewInit() {
  this.aUser.nativeElement.addEventListener('click', this._clickHandler); 
}  

to unsubscribe use

this.aUser.nativeElement.removeEventListener('click', this._clickHandler); 

See also Dynamically add event listener


I would suggest you write a handler that performs the conditional action, this is the simplest way IMHO :

In Component template :

<a class='user' (click)="myClickHandler($event)"></a>

in Component code .ts :

myClickHandler(event): void {
  if (this.isOverflown) {
    this.menu.toggle(event);
  }
}

EDIT after comment : if you really want to avoid binding (I don't understand why, but anyway) you can have a conditional component using *ngIf:

<a class='user' *ngIf="isOverflown" (click)="menu.toggle($event)"></a>
<a class='user' *ngIf="!isOverflown"></a>

You can just do it like this

<a class='user' (click)="isOverflown && menu.toggle($event)"></a>

Tags:

Angular