Skip to content

Instantly share code, notes, and snippets.

@christo8989
Created March 20, 2020 22:08
Show Gist options
  • Save christo8989/842771addf8ac394e207ebc4c3171b1d to your computer and use it in GitHub Desktop.
Save christo8989/842771addf8ac394e207ebc4c3171b1d to your computer and use it in GitHub Desktop.
Angular Directives
import {
Directive,
Input,
OnDestroy,
EventEmitter,
Output,
} from '@angular/core';
import { NgModel } from '@angular/forms';
import { Subscription, Observable } from 'rxjs';
import { debounceTime, distinctUntilChanged } from 'rxjs/operators';
@Directive({
selector: '[ngModel][debounce]',
providers: [NgModel],
})
export class DebounceDirective implements OnDestroy {
private sink = new Subscription();
@Input() time = 400; // NOTE: milliseconds
@Output() debounce = new EventEmitter<any>(true);
private debouncer: Observable<any>;
constructor(private model: NgModel) {}
ngOnInit() {
this.debouncer = this.model.control.valueChanges.pipe(
debounceTime(this.time),
distinctUntilChanged(),
);
this.sink.add(
this.debouncer.subscribe(a => {
this.debounce.emit(this.model.control.value);
}),
);
}
ngOnDestroy() {
this.sink.unsubscribe();
}
}
import { Directive, ElementRef, AfterViewInit } from '@angular/core';
import { NgModel } from '@angular/forms';
@Directive({
selector: '[focusOnInit]',
providers: [NgModel],
})
export class FocusOnInitDirective implements AfterViewInit {
private readonly allowedTypes = ['text', 'date', 'number', 'tel'];
constructor(private el: ElementRef<HTMLInputElement>) {}
ngAfterViewInit() {
if (
!(this.el.nativeElement instanceof HTMLInputElement) ||
!this.allowedTypes.includes(this.el.nativeElement.type)
) {
console.error(
`The focusOnInput directive must attach to an HTMLInputElement of types: ${this.allowedTypes.join(
', ',
)}`,
);
}
setTimeout(() => {
this.el.nativeElement.focus();
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment