Angular2 remove click event binding after first click Angular2 remove click event binding after first click typescript typescript

Angular2 remove click event binding after first click


Method 1:

You can set a boolean variable, so if the user calls the function, boolean value changes and the user will be able to call the function on click again but actually nothing will happen.

bool: boolean = true;doSomething($event) {  if (this.bool) {    // My method logic goes here    ...    ...    console.log('Method Logic');    this.bool = false;  }}

Method 2:

You can add a condition to your html component, if specified variable (in this case bool) is true, the function is going to be executed, but only once because the bool variable will be set to false and the click function will execute nothing (null) from now on.

bool: boolean = true;doSomething($event) {  // My method logic goes here  ...  ...  console.log('Method Logic');  this.bool = false;}

(click)="bool ? doSomething($event) : null"


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.

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();    // ...  }}

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>


For people dealing with Observable / Subject for handling some events :

<button (click)="clickEvents$.next($event)">
class MyComponent {  clickEvents$ = new Subject<MouseEvent>();  firstClick$ = this.clickEvents.take(1); // Observable of first click}