替换在按键事件中不起作用的符号



我有需要删除非数字符号的输入

组件

的html
<input
type="text"
tabindex="0"
class="search__input form-control-md + {{ class }}"
[value]="config.value"
[required]="config.required"
[attr.maxlength]="config.maxLength"
[attr.minLength]="config.minLength"
(focusout)="onFocusOut($event)"
(input)="onValueChange($event)"
(keypress)="onValueChange($event)"
(keyup.enter)="onEnter($event)"
#inputElem
/>

组件

export class TextFieldComponent implements OnInit, ControlValueAccessor {
@Input() config: FormBase<string>;
@Input() form: FormGroup;
@Output() onChanged = new EventEmitter<boolean>();
@Input() class: string;
configControl = new FormControl();
@Input() set value(value: string) {
this._value = value;
}
get value(): string {
return this._value;
}
private _value: string;
constructor() {}
ngOnInit() {}
onFocusOut(event) {
this.onValueChange(event);
this.onChanged.emit(true);
}
onEnter(event) {
this.onValueChange(event);
this.onChanged.emit(true);
}
onValueChange(event) {
this.changeValue(event.target.value);
}
writeValue(value) {
this.value = value;
}
changeValue(value) {
if (this.value === value) {
return;
}
this.value = value;
let result;
switch (this.config.isNumber) {
case true:
result = value != null ? value.toString().replace(/[^0-9]/g, "") : null;
console.log(result);
this.onChange(result);
break;
default:
this.onChange(value);
}
}
onChange: any = () => {};
onTouched: any = () => {};
registerOnChange(fn) {
this.onChange = fn;
}
registerOnTouched(fn) {
this.onTouched = fn;
}
}

我的问题,例如,在focusout上,这种方法changeValue工作得很好,它删除了非数字符号,但在keypress事件上,我看到在控制台上我已经替换了值,但在输入时,我仍然看到字母。我该如何解决这个问题?

您需要了解这里的按键是做什么的。当按下产生字符值的键时触发keypress事件,产生字符值的键的示例有字母键、数字键和标点键。

不产生字符值的键的例子是修改键,如Alt, Shift, Ctrl或Meta。

在上面的例子中,按键事件不会被调用,只有当字符值产生时才会被调用。

您应该使用keyUpkeyDown事件来更有效地跟踪事情。

注意:检查这个链接的差异b/w keyup, keydown和keypress。

在你的组件访问输入元素使用ViewChild

@ViewChild('inputElem') inputEl: ElementRef;

然后在替换

后设置结果
result = value != null ? value.toString().replace(/[^0-9]/g, '') : null;
// update input value
this.inputEl.nativeElement.value = result;
console.log(result);

演示

最新更新