how to change value of input before formControl directive get it in angular

2.2k Views Asked by At

need to convert persian numbers to english ones in this input <input type="text" formControlName="mobile" myCustomDirective />. so created a directive, with entering Persian number events fire with that value, then I change it to English number and again all events fire with English one. if I prevent events from firing for the second change it's wrong because I need events fire with English number. actually, I need to get the value of the input and change it to English before FormControl directive catches it. is there any solution?

1

There are 1 best solutions below

0
On

finally I could resolve my question:

import { DecimalPipe } from '@angular/common';
import { Directive, ElementRef, forwardRef, HostListener } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
@Directive({
selector: '[appInputConvertNumbers]',
providers: [
 {
  provide: NG_VALUE_ACCESSOR,
  useExisting: forwardRef(() => InputConvertNumbersDirective),
  multi: true
 },
  DecimalPipe
]
})
export class InputConvertNumbersDirectiveimplements ControlValueAccessor {
private _onChange: (value: any) => {};
  constructor(private _elementRef: ElementRef) { }
  @HostListener('input') onInput() {
    let value = this._elementRef.nativeElement.value;
    let newValue = this.setInputValue(value);
    this._onChange(newValue);
  }
  private setInputValue(value: string): string {
    value = value.replace(/[۰-۹]/g, number => '۰۱۲۳۴۵۶۷۸۹'.indexOf(number).toString())
    this._elementRef.nativeElement.value = value;
    return value;
  }
  writeValue(value: string): void {
    this.setInputValue(value);
  }
  registerOnChange(fn: any): void {
    this._onChange = fn;
  }
  registerOnTouched(fn: any): void {
  }
}

and simply in the form I can use this directive

<form [formGroup]="exampleForm">
  <input appInputConvertNumbers formControlName="number">
</form>