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
Had a similar issue, this worked for me:
<p (click)="item.isClickable ? item.onClick() : return;">
Hello Mom!
</p>
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}">
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
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 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)
You can just do it like this
<a class='user' (click)="isOverflown && menu.toggle($event)"></a>