Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditionally apply click event in Angular 4

Tags:

angular

Is it possible to define a condition in the template based on which a click handler is attached?

For instance, the closest I can get is evaluating a condition at the entry of the click method.

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

Is there a way in which I can avoid binding to the click event altogether if the flag isOverflown is false?

Also, I dont want to use ng-if on the element and duplicate the template. ie: create one element that has click binding and create another that doesn't, then show/hide them using ng-if

like image 603
Himanshu Arora Avatar asked Aug 31 '17 15:08

Himanshu Arora


2 Answers

You can just do it like this

<a class='user' (click)="isOverflown && menu.toggle($event)"></a> 
like image 131
internetzer Avatar answered Sep 30 '22 09:09

internetzer


There is no way to do 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 in Angular 2

like image 37
Günter Zöchbauer Avatar answered Sep 30 '22 09:09

Günter Zöchbauer