I'd like to know how can I create a mask with regex expression for input field.
I need to add some masks to a field, such as: yyyy/yyyy. This sounds like a period.
I saw a link that creates a mask using the pipe from Angular2. Here is the link.
So, I'd like to create a pipe with a different regex expression to allow the user writes only this: yyyy/yyyy ; and using transform method from pipe. Is this possible?
Here is my pipe and formatter:
import { Pipe, PipeTransform } from "@angular/core";
@Pipe({ name: "mypipe" })
export class MyPipe implements PipeTransform {
private SEPARATOR: string;
constructor() {
this.SEPARATOR = "/";
}
transform(value): string {
let integer = (value || "").toString();
// Here is where the code should be, to transform the value
return integer;
}
transform(value): string {
// parse method
}
}
import { Directive, HostListener, ElementRef, OnInit } from "@angular/core";
// import { MyPipe } from ...
@Directive({ selector: "[myFormatter]" })
export class MyFormatterDirective implements OnInit {
private el: HTMLInputElement;
constructor(
private elementRef: ElementRef,
private mypipe: MyPipe
) {
this.el = this.elementRef.nativeElement;
}
ngOnInit() {
this.el.value = this.mypipe.transform(this.el.value);
}
@HostListener("keydown", ["$event.target.value"])
handleKeyboardEvent(value) {
this.el.value = this.mypipe.transform(value);
}
}