'Conditionally apply click event in Angular 4
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
Solution 1:[1]
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
Solution 2:[2]
You can just do it like this
<a class='user' (click)="isOverflown && menu.toggle($event)"></a>
Solution 3:[3]
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>
Solution 4:[4]
Had a similar issue, this worked for me:
<p (click)="item.isClickable ? item.onClick() : return;">
Hello Mom!
</p>
Solution 5:[5]
You need to inject ElementRef
and Renderer
into your component and use its listen
method on the element reference of interest.
https://angular.io/api/core/Renderer
https://angular.io/api/core/Renderer2
this.renderer.listen(this.elementRef.nativeElement, 'click', callbackFunction)
Solution 6:[6]
Just binding null with the help of ternary operator and adding disabled class resolved my problem.
<a (click)="item.quantity>1 ? decreaseQuantity():null;" [ngClass]="{'disabled': item.quantity<=1}">
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | rofrol |
Solution 2 | internetzer |
Solution 3 | Philipp Meissner |
Solution 4 | Craig Wayne |
Solution 5 | |
Solution 6 | Shyam Narayan |