Skip to content

Instantly share code, notes, and snippets.

@dmsysop
Created August 29, 2017 03:32
Show Gist options
  • Save dmsysop/f891b15247dcf2991bde6860767cb799 to your computer and use it in GitHub Desktop.
Save dmsysop/f891b15247dcf2991bde6860767cb799 to your computer and use it in GitHub Desktop.
import { Directive, HostListener, Input, ElementRef, forwardRef } from '@angular/core';
import { NG_VALUE_ACCESSOR, ControlValueAccessor } from '@angular/forms';
@Directive({
selector: "[cep]", //selector de atributo
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => CepDirective),
multi: true
}
]
})
export class CepDirective implements ControlValueAccessor {
constructor(private element: ElementRef) { }
onChange: any
@HostListener('input')
onInput() {
const input = this.element.nativeElement as HTMLInputElement
input.value = this.parseValue(input.value)
this.onChange(input.value)
}
parseValue(value) {
value = value.replace(/-/g, '')
if (value.length > 8) {
value = value.substr(0, 8)
}
let sections = []
sections.push(value.substr(0, 5))
if (value.length > 5) {
sections.push(value.substr(5, 3))
}
return sections.join('-')
}
/**
* Write a new value to the element.
*/
writeValue(value: any): void {
this.element.nativeElement.value = this.parseValue(value)
}
/**
* Set the function to be called when the control receives a change event.
*/
registerOnChange(fn: any): void {
this.onChange = fn
}
/**
* Set the function to be called when the control receives a touch event.
*/
registerOnTouched(fn: any): void { }
/**
* This function is called when the control status changes to or from "DISABLED".
* Depending on the value, it will enable or disable the appropriate DOM element.
*
* @param isDisabled
*/
setDisabledState?(isDisabled: boolean): void { }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment