Conditionally apply click event in Angular 4

后端 未结 6 1011
执笔经年
执笔经年 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: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

提交回复
热议问题