Skip to content

Instantly share code, notes, and snippets.

@Osmandiyaka
Last active April 17, 2020 21:04
Show Gist options
  • Save Osmandiyaka/bb8eef88559ab52997c78c5b8e42de18 to your computer and use it in GitHub Desktop.
Save Osmandiyaka/bb8eef88559ab52997c78c5b8e42de18 to your computer and use it in GitHub Desktop.
Using rxjs to adapt a click event to a double click in angular
Let assume you have a third party angular component, myExtComp and you are using it in your own component like this:
<myExtComp (onItemClicked)="myItemClicked($event)"> </myExtComp>
Notice the third party component exposes only a click event. What if instead of the click event, you would like to
listen for a double click event. Well with rxjs, this is very trivial. Look at how you can adapt an external click
event into a double click event in angular using rxjs
import { Component, OnInit, ViewChild, ViewEncapsulation, ChangeDetectorRef, AfterViewInit, Injector } from '@angular/core';
import { Subject, fromEvent, asyncScheduler } from 'rxjs';
import { debounceTime, map, distinctUntilChanged, filter, buffer, } from 'rxjs/operators';
@Component({
selector: 'app-my',
templateUrl: './my.component.html',
styleUrls: ['./my.component.css'],
encapsulation: ViewEncapsulation.None
})
export class MyComponent extends Component implements OnInit {
doubleClickEvent=new Subject<any>();
constructor( ) { }
ngOnInit() {
this.doubleClickEvent
.pipe(
buffer(this.doubleClickEvent.pipe(debounceTime(250))),
filter(clicks => clicks.length === 2),
map(clicks => clicks[0])
).subscribe(event=>{
console.log(event)
});
}
private myItemClicked(event: any) {
this.doubleClickEvent.next(event);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment