Last active
March 2, 2020 11:08
-
-
Save nakulvijay56/e2c913a18270b2718f14cd8330bf7eae to your computer and use it in GitHub Desktop.
Angular : This is a custom directive to remove matching regex pattern from ngModel inputs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Directive, HostListener, Input, OnChanges, Optional } from '@angular/core'; | |
import { NgModel } from '@angular/forms'; | |
/** | |
* @description | |
* | |
* This is a custom directive to remove matching regex pattern from ngModel inputs | |
* | |
* eg: | |
* (will remove character matching the default regular expression present in the directive) | |
* 1. <input type="text" [(ngModel)]="componentVaribale" name="name1" appRmPattern> | |
* (will remove character matching the given regular expression) | |
* 2. <input type="text" [(ngModel)]="componentVaribale" name="name2" appRmPattern="/^[abc]/"> | |
*/ | |
@Directive({ | |
selector: '[appRmPattern]' | |
}) | |
export class RmPatternDirective implements OnChanges { | |
private pattern = /[^\w\d\s\_\-]/gm; // default pattern | |
@Input('appRmPattern') userPattern: string; | |
constructor(@Optional() public model: NgModel) { | |
if (!model){throw new Error ("myCustomDirective requires ngModel.");} | |
} | |
ngOnChanges() { | |
if (this.userPattern) { | |
var regParts = this.userPattern.match(/^\/(.*?)\/([gim]*)$/); | |
if (regParts) { | |
// pattern with delimiters and modifiers | |
this.pattern = new RegExp(regParts[1], regParts[2]); | |
} else { | |
// pattern without delimiters | |
this.pattern = new RegExp(this.userPattern); | |
} | |
} | |
} | |
@HostListener('input', ["$event"]) onUserInput(event) { | |
event.target.value = event.target.value.replace(this.pattern, ''); | |
if (this.model) { | |
this.model.update.emit(event.target.value); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment