0
votes

I have an angular Application with multiple Buttons which have specific IDs. each of them has a click function and I want to track if a user clicked the Button without changing anything in each of the Methods.

example code:

  import { Component, ViewChild, ElementRef } from '@angular/core';
import { Observable } from 'rxjs';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  
  
  

    @ViewChild('BUTTON_EDIT', {read: ElementRef}) BUTTON_EDIT;
      @ViewChild('BUTTON_ADD', {read: ElementRef}) BUTTON_ADD;
      ele: Element;
      
      ngAfterViewInit(): void {
        let clickStream;
    
        //check which element was pressed and get the id
        //how can i check it?

        clickStream = fromEvent(this.ele, 'clicked');
        var id = this.ele.id;
    
        clickStream.subscribe(event => {
          //send info
        });
      }
    }
2
This code is not working ? where is the problem ? and what is the error you are getting ?Abhinav Kumar
this is just an example, i want to know if and how it is possible to do thatVincent Mach
Unrelated to question, but AFAIK the event must be click: fromEvent(this.ele, 'click')Michael D

2 Answers

1
votes

You can use merge, which

Turn multiple observables into a single observable

ngAfterViewInit(): void {
    merge(
        fromEvent(this.BUTTON_EDIT.nativeElement, 'click'),
        fromEvent(this.BUTTON_ADD.nativeElement, 'click'),
    ).subscribe((event: Event)=> {
      console.log(event.target.id);
    });
  }

There is also an article which explains details https://www.tektutorialshub.com/angular/create-observable-from-event-using-fromevent-in-angular/

For emitted Event there is target property, from where you can get a target, there is a fiddle https://jsfiddle.net/a907jf5g/

Angular approach would be something like:

@Component({
  template: `
    <button (click)="add()">Add</button>
    <button (click)="edit()">Edit</button>
  `,
})
export class MyComponent {
  add() {
    // add clicked
  }

  edit() {
    // edit clicked
  }
}
1
votes

Angular allows you to bind more than one method to a click event. This means you can bind a common "click" method that takes in the element's ID and does not modify the event handler method that is specific to that button as follows:

<button id="add-btn" #addBtn (click)="click(addBtn.id); add()">
  Add
</button>

<button id="edit-btn" #editBtn (click)="click(editBtn.id); edit()">
  Edit
</button>

The click method does the tracking of all button clicks while the add and edit method are the event handlers that are specific to each button.

StackBlitz Example