import { OnInit, Directive, HostListener, HostBinding, ElementRef } from "@angular/core";
import { NgModel } from "@angular/forms";
@Directive({
selector: "[ngModel][ipAddressMask]",
providers: [NgModel]
})
export class IpAddressMaskDirective implements OnInit {
navKeys = [39, 37, 8, 46, 65, 97] // Delete, Backspace, <- , ->, ctrl+a tuşlarını çıkarıyoruz
ipMaskChars = ["_", ".", "_", ".", "_", ".", "_"];
ipMask = "_._._._"
@HostBinding('attr.value') _value;
constructor(private elem: ElementRef, private model: NgModel) { }
@HostListener("keyup", ['$event']) hostKeyUpEvent($event: KeyboardEvent) {
let key = $event.key;
let code = +$event.keyCode;
debugger
if (!key) return;
let val = this.elem.nativeElement.value;
if (this.navKeys.indexOf(code) > -1) return;
let numReg = new RegExp("[0-9]");
let parts = val.split(".");
for (let i in parts)
parts[i] = parts[i].replace(/[^0-9\.]+/g, '');;
let outPut = parts.filter(c => Number(c));
if (!outPut) return;
let newValue = this.format(outPut);
this.elem.nativeElement.value = newValue;
this.model.viewToModelUpdate(newValue);
let SelectionPosition = this.getSelectionPosition(newValue);
this.elem.nativeElement.selectionStart = SelectionPosition;
this.elem.nativeElement.selectionEnd = SelectionPosition;
}
private getSelectionPosition(inputVal: string): number {
let position = 0;
if (inputVal) {
let parts = inputVal.split(".");
let outPut = parts.filter(c => Number(c));
if (parts && outPut) {
position += outPut.length;
for (let i = 0; i < outPut.length; i++) {
position += (outPut[i] + "").length > 3 ? 3 : (outPut[i] + "").length;
}
position--;
}
}
return position;
}
private format(outPut: string[]) {
let ipAddressChars = [];
let outPutLength = outPut && outPut.length;
debugger;
for (let i = 0; i < 4; i++) {
if (outPutLength > i) {
if ((outPut[i] + "").length > 3) {
if (i + 1 < 4) {
if (outPut[i + 1]) {
outPut[i + 1] = (outPut[i] + "").slice(3) + outPut[i + 1]
} else {
outPut[i + 1] = (outPut[i] + "").slice(3);
outPutLength = outPut.length;
}
outPut[i] = (outPut[i] + "").slice(0, 3);
} else {
outPut[i] = (outPut[i] + "").slice(0, 3);
}
}
if (+outPut[i] < 0) outPut[i] = "0";
else if (+outPut[i] > 255) outPut[i] = "255";
ipAddressChars.push(outPut[i]);
} else {
ipAddressChars.push("___");
}
}
return ipAddressChars.join(".");
}
ngOnInit(): void {
this._value = this.ipMask;
}
}
Hiç yorum yok:
Yorum Gönder