[英]how to change value of input before formControl directive get it in angular
need to convert persian numbers to english ones in this input <input type="text" formControlName="mobile" myCustomDirective />
.需要在此输入
<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.实际上,我需要在
FormControl
指令捕获它之前获取输入的值并将其更改为英文。 is there any solution?有什么解决办法吗?
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.