Skip to content

Instantly share code, notes, and snippets.

@erickvieira
Last active February 13, 2020 16:55
Show Gist options
  • Save erickvieira/0385e09a61349deedfaeafe75dadb517 to your computer and use it in GitHub Desktop.
Save erickvieira/0385e09a61349deedfaeafe75dadb517 to your computer and use it in GitHub Desktop.
Angular 7|8|9 LongPressDirective with RxJS
import { Component } from '@angular/core';
@Component({
selector: 'app',
template: `
<div long-press [debounce]="2000" (onLongPress)="logEvent($event)">
Press me for 2 seconds
</div>
`,
styles: [`
.press-me {
padding: 4px 8px;
background-color: black;
color: lime;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
font-size: 30px;
}
`]
})
export class AppComponent {
readonly logEvent = console.info;
constructor() {}
}
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { LongPressModule } from './directives/long-press/long-press.module';
@NgModule({
declarations: [
AppComponent,
],
imports: [
BrowserModule,
LongPressModule,
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
import { Platform } from '@ionic/angular';
import { mergeMap, delay, takeUntil } from 'rxjs/operators';
import { Observable, fromEvent, of } from 'rxjs';
import { Directive, EventEmitter, Input, Output, ElementRef } from '@angular/core';
@Directive({
selector: '[long-press]'
})
export class LongPressDirective {
@Input() debounce: number = 500;
@Output() onLongPress = new EventEmitter<MouseEvent>();
private mouseUp$: Observable<MouseEvent>;
private mouseDown$: Observable<MouseEvent>;
private longPress$: Observable<MouseEvent>;
constructor(el: ElementRef, platform: Platform) {
if (platform.is('android') || platform.is('ios')) {
const emitLongPress = () => {
setTimeout(() => {
this.onLongPress.emit(null);
}, 100);
return false;
}
window.oncontextmenu = emitLongPress;
}
const target = el.nativeElement;
this.mouseUp$ = fromEvent(target, 'mouseup');
this.mouseDown$ = fromEvent(target, 'mousedown');
this.longPress$ = this.mouseDown$.pipe(
mergeMap(e => of(e).pipe(
delay(this.debounce),
takeUntil(this.mouseUp$),
))
);
// updating the status
this.longPress$.subscribe(event => this.onLongPress.emit(event));
}
}
import { LongPressDirective } from './long-press.directive';
import { NgModule, CUSTOM_ELEMENTS_SCHEMA} from '@angular/core';
import { CommonModule } from '@angular/common';
@NgModule({
imports: [
CommonModule,
],
exports: [
LongPressDirective,
],
declarations: [
LongPressDirective,
],
schemas: [
CUSTOM_ELEMENTS_SCHEMA,
]
})
export class LongPressModule { }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment