Conditionally apply click event in Angular 4

后端 未结 6 954
执笔经年
执笔经年 2020-12-03 16:56

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

相关标签:
6条回答
  • 2020-12-03 17:09

    Had a similar issue, this worked for me:

    <p (click)="item.isClickable ? item.onClick() : return;">
     Hello Mom!
    </p>
    
    0 讨论(0)
  • 2020-12-03 17:14

    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}">
    
    0 讨论(0)
  • 2020-12-03 17:16

    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

    0 讨论(0)
  • 2020-12-03 17:21

    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>
    
    0 讨论(0)
  • 2020-12-03 17:28

    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)

    0 讨论(0)
  • 2020-12-03 17:29

    You can just do it like this

    <a class='user' (click)="isOverflown && menu.toggle($event)"></a>
    
    0 讨论(0)
提交回复
热议问题