我輸入了需要洗掉非數字符號的地方
這是組件的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事件中我看到在控制臺上我已經替換了值,但是在輸入時,我仍然看到字母。我該如何解決這個問題?
uj5u.com熱心網友回復:
您需要了解keypress在這里做什么。當按下產生字符值的鍵并且產生字符值的鍵的示例是字母、數字和標點符號時,會觸發 keypress 事件。
不產生字符值的鍵的示例是修飾鍵,例如 Alt、Shift、Ctrl 或 Meta。
在上述情況下,keypress 事件不會呼叫,只會在生成字符值時呼叫。
您應該使用keyUp或keyDown事件來更有效地跟蹤事物。
注意:檢查此鏈接以了解黑白 keyup、keydown 和 keypress 的區別。
uj5u.com熱心網友回復:
在您的組件中使用 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);
演示
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/317151.html
標籤:javascript 有角的 打字稿
上一篇:Angular服務-型別“void”不可分配給型別“Project[]”
下一篇:打字稿:從聯合型別中排除未定義
