简体   繁体   中英

How can i use fromEvent (Angular rxjs) with multiple Elements?

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

In order to listen to multiple events you can usemerge , 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 - Create Observable from Event using FromEvent in Angular which explains details.

Events in Web APIs

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

Angular approach to listen to click event

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

  edit() {
    // edit clicked
  }
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM