Skip to content

Instantly share code, notes, and snippets.

@avoliva
Last active June 3, 2019 21:59
Show Gist options
  • Save avoliva/aa215102139d51f7feffdb0bd20424c0 to your computer and use it in GitHub Desktop.
Save avoliva/aa215102139d51f7feffdb0bd20424c0 to your computer and use it in GitHub Desktop.
Angular enter submit directive
import { ElementRef, OnInit, Directive, Input } from '@angular/core';
import { Observable, fromEvent } from 'rxjs';
import { distinctUntilChanged, filter, merge } from 'rxjs/operators';
@Directive({
selector: 'input',
// selector: '[enter-submit]',
})
export class EnterSubmit implements OnInit {
@Input() eventName: string = 'keyup';
constructor(private elementRef: ElementRef) {
}
ngOnInit(): void {
const keyUps = fromEvent(this.elementRef.nativeElement, this.eventName);
const eventStream = keyUps.pipe(
merge(keyUps),
filter((e: KeyboardEvent) => {
return e.keyCode === 13;
}),
distinctUntilChanged((x, y) => {
return x.type == y.type;
})
)
eventStream.subscribe(
input => {
// do your thing
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment