Skip to content

Instantly share code, notes, and snippets.

@TyGuy
Created April 26, 2017 00:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TyGuy/2f45c56fc5df07db7683bd5725c5fb4c to your computer and use it in GitHub Desktop.
Save TyGuy/2f45c56fc5df07db7683bd5725c5fb4c to your computer and use it in GitHub Desktop.
Custom Press Directives in Ionic 2
/*
import { Everything } from './everywhere'
... etc.
*/
// import the directives:
import { LongPressDirective } from '../directives/long-press.directive'
import { QuickPressDirective } from '../directives/quick-press.directive'
/*...*/
// declare the directives:
@NgModule({
declarations: [
LongPressDirective,
QuickPressDirective,
/*...*/
],
/*...*/
})
import { Directive, ElementRef, OnInit, OnDestroy, Output, EventEmitter } from '@angular/core'
import { Gesture } from 'ionic-angular/gestures/gesture'
declare var Hammer;
@Directive({
selector: '[longPress]'
})
export class LongPressDirective implements OnInit, OnDestroy {
el: HTMLElement;
pressGesture: Gesture;
@Output('longPress') onPress: EventEmitter<any> = new EventEmitter();
constructor(el: ElementRef) {
this.el = el.nativeElement;
}
ngOnInit() {
const pressOptions = {
recognizers: [
[Hammer.Press, { time: 1000 }]
]
}
this.pressGesture = new Gesture(this.el, pressOptions);
this.pressGesture.listen();
this.pressGesture.on('press', e => {
this.onPress.emit(e);
})
}
ngOnDestroy() {
this.pressGesture.destroy();
}
}
<div (longPress)="longPressed()" (quickPress)="quickPressed()" (quickPressUp)="quickPressUpped()">
<!-- ... -->
</div>
@Component({
selector: 'my-component',
templateUrl: 'my-component.html'
})
export class MyComponent {
/*...*/
quickPressed() {
console.log('quick pressed!')
}
quickPressUpped() {
console.log('quick press upped!')
}
longPressed() {
console.log('long press!')
}
}
import { Directive, ElementRef, OnInit, OnDestroy, Output, EventEmitter } from '@angular/core'
import { Gesture } from 'ionic-angular/gestures/gesture'
declare var Hammer;
@Directive({
selector: '[quickPress]'
})
export class QuickPressDirective implements OnInit, OnDestroy {
el: HTMLElement;
pressGesture: Gesture;
@Output('quickPress') onPress: EventEmitter<any> = new EventEmitter();
@Output('quickPressUp') onPressUp: EventEmitter<any> = new EventEmitter();
constructor(el: ElementRef) {
this.el = el.nativeElement;
}
ngOnInit() {
const pressOptions = {
recognizers: [
[Hammer.Press, { time: 100 }]
]
}
this.pressGesture = new Gesture(this.el, pressOptions);
this.pressGesture.listen();
this.pressGesture.on('pressup', e => {
this.onPressUp.emit(e)
})
this.pressGesture.on('press', e => {
this.onPress.emit(e);
})
}
ngOnDestroy() {
this.pressGesture.destroy();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment