Angular2 remove click event binding after first click

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

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

From the method, is doSomethingthere a way to remove the event (click)from the button (so that the user can no longer activate the function)?

I tried to set the disabled support button, but did not change the behavior of Angular2.

I tried to use (click)="doSomething($event)and then

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');
    });
}

But it does not "replace" the click event. Thus, after clicking the button, both the initial logic and the click block console log are launched.

+4
source share
3 answers

Method 1 :

boolean, , , boolean , , .

bool: boolean = true;

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

2:

html, ( bool) , , , bool ​​ false click (null) .

bool: boolean = true;

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

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

+5

, Angular , .

, Renderer. , :

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. ng2-events [ ], :

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

, Observable/Subject :

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

Source: https://habr.com/ru/post/1665565/


All Articles