Skip to content

Instantly share code, notes, and snippets.

@r2dev
Last active March 1, 2019 20:07
Show Gist options
  • Save r2dev/fba7f44503f00bfedb41239b71eea0fb to your computer and use it in GitHub Desktop.
Save r2dev/fba7f44503f00bfedb41239b71eea0fb to your computer and use it in GitHub Desktop.
Angular 2 cleave.js phone component
import { Directive, Input, forwardRef, ElementRef, AfterViewInit, OnDestroy } from '@angular/core';
import { NG_VALUE_ACCESSOR, ControlValueAccessor } from '@angular/forms'
import Cleave from 'cleave.js'
@Directive({
selector: '[phone-input]',
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => PhoneNumberInputDirective),
multi: true
}
],
host: {
'(blur)': 'onTouched()'
}
})
export class PhoneNumberInputDirective
implements AfterViewInit, OnDestroy, ControlValueAccessor {
public initialValue = null;
public cleave = null;
onChanged = (_: any) => { };
onTouched = (_: any) => { };
private componentInitialized = false
constructor(private _elementRef: ElementRef) { }
ngAfterViewInit() {
const that = this;
if (!this.cleave) {
this.cleave = new Cleave(this._elementRef.nativeElement, {
blocks: [3, 3, 4],
delimiter: '-',
numericOnly: true,
onValueChanged: function (e) {
if (that.initialValue === null) {
that.onChanged(e.target.rawValue);
}
}
});
this.componentInitialized = true;
if (this.initialValue !== null) {
this.cleave.setRawValue(this.initialValue);
//setRawValue without trigger onValueChanged event
this.initialValue = null;
}
}
}
writeValue(value) {
if (this.cleave) {
this.cleave.setRawValue(value);
}
if (value !== null && value !== undefined && this.componentInitialized === false) {
this.initialValue = value;
}
}
ngOnDestroy() {
if (this.cleave) {
this.cleave.destroy();
}
}
registerOnChange(fn: (_: any) => void) {
this.onChanged = fn;
}
registerOnTouched(fn: (_: any) => void) {
this.onTouched = fn;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment