本文介绍了首次单击后,Angular2删除单击事件绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,我有一个单击按钮的按钮:

In my application I have a button with a click even on it:

<button class="btn btn-default" (click)="doSomething()">

doSomething 方法中,有没有从按钮中删除(点击)事件的任何方式(这样用户就不能再触发功能?)。

From within the doSomething method, is there any way to remove the (click) event from the button (so the user can't trigger the functionnality anymore?).

我试图在按钮上设置一个禁用道具,但它不会改变Angular2行为。

I tried to set a disabled prop on the button but it doesn't change Angular2 behavior.

我试图使用(点击)=doSomething($ event)然后

doSomething($event) {
  // My method logic goes here
  ...
  ...
  console.log('Method Logic');

  //Attempt to overwrite click event
  let target = event.target || event.srcElement || event.currentTarget;
  this.renderer.listen(target, 'click', (event) => {
      console.log('clic block');
    });
}

但它并没有替换click事件。所以在那之后,点击时,原始逻辑和click block控制台日志都会被触发!

But It doesn't "replace" the click event. So after that, on click, both original logic and the "click block" console log are triggered!

解决方案

为执行添加一个保护变量的缺点是实际的事件监听器仍然存在并且在点击时会触发Angular的变化检测,即使它没有做任何事情。

The downside of just adding a guard variable for the execution is that the actual event listener is still in place and will trigger Angular's change detection when clicked, even though it doesn't do anything.

要实际删除事件监听器,必须通过组件的 Renderer 添加它。这将返回一个函数,在调用时删除事件监听器:

To actually remove the event listener, you have to add it via the component's Renderer. This will return a function that removes the event listener when called:

import {Component, AfterViewInit, Renderer, ViewChild, ElementRef} from '@angular/core';

@Component({
  template: `<button #button>...</button>`
})
export class SampleComponent implements AfterViewInit {

  @ViewChild('button') button: ElementRef;
  private cancelClick: Function;

  constructor(private renderer: Renderer) {}

  ngAfterViewInit() {
    this.cancelClick = this.renderer.listen(this.button.nativeElement, 'click',
      ($event: any) => this.handleClick($event));
  }

  handleClick($event: any) {
    this.cancelClick();
    // ...
  }
}

如果你的话目标是在第一次触发事件时删除事件侦听器,这可以作为Angular事件系统的插件实现。我将其添加为实用程序库,现在让您执行以下操作:

If your goal is to just remove the event listener when the event is fired for the first time, this can be implemented as a plugin to Angular's event system. I added it as a part of my ng2-events utility library [source], which lets you now do the following:

<button (once.click)="handleClick($event)">...</button>

这篇关于首次单击后,Angular2删除单击事件绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 03:58