Friday, 5 April 2019

Angular Directive Example to Allow Certain Values

Below is an example of an Angular 6 Directive. This directive detects changes in NgModel as user enters in input value and only allows specific value to be entered while rejecting the others.
import { Directive } from '@angular/core';
import { NgModel } from '@angular/forms';

@Directive({
  selector: '[ngModel][my-directive]',
  providers: [NgModel],
  host: {
    '(ngModelChange)': 'onInputChange($event)'
  } 
})
export class MyDirective {

  constructor(private model: NgModel) { }

  onInputChange(value) {
    console.log(value);
    
    this.model.valueAccessor.writeValue(value.replace(/[^\d\.\,\s]+/g, ''));
  }
}

Then to use it on HTML part:
<input name="productPrice" [(ngModel)]="price" my-directive />

No comments: