本文介绍了有条件地在Angular 4中应用click事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在模板中定义附加点击处理程序的条件?

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

例如,我能得到的最接近的结果是在click方法的入口处评估条件.

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>

如果标志isOverflown为false,是否可以完全避免绑定到click事件?

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

此外,我不想在元素上使用ng-if并复制模板.即:创建一个具有click绑定的元素,并创建一个没有click绑定的元素,然后使用ng-if

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

推荐答案

无法进行启用/禁用绑定.

There is no way to do enable/disable bindings.

有可能必须这样做

@ViewChild('.user') aUser:ElementRef;

clickHandler(event) {
  console.log(event);
}
_clickHandler = this.clickHandler.bind(this);

ngAfterViewInit() {
  this.aUser.nativeElement.addEventListener('click', this._clickHandler);
}

退订使用

this.aUser.nativeElement.removeEventListener('click', this._clickHandler);

另请参见在Angular 2中动态添加事件侦听器

这篇关于有条件地在Angular 4中应用click事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 09:04