I have an input field where the requirement is that it has 0 initially set on change of value that 0 is removed and number is added but that 0 is removed only if key pressed by user is a number now the issue arises that when I do use a input event it take my value as sing quoted string as ‘8’ i had used replace method but what if I press backspace also on focus out it adds a .00 to a number if its there but i am also found a issue when my number is initially 0 and i press a nonnumberic value it makes my number set ” and also on backspace keypress it should allow backspace and remove zero but should not give an error when I remove the last not 0 number after typing something and do a backspace it gives error as Cannot read properties of null (reading ‘replace’) that is also case so its a mix of various cases
<input type="text" class="someclass" [readOnly]="isView || isEdit" placeholder=""
formControlName="somename" mask="separator.2" thousandSeparator="," (input)="removeZeroOnKeydown($event)"
(focusout)="onFixedAmount('somename')" separatorLimit="99999999999999">
<label class="label">Some Label$</label>
removeZeroOnKeydown(event: InputEvent) {
let inputElement = event.target as HTMLInputElement;
//Get FormControl Name on keydown
let controlName = inputElement.getAttribute('formControlName');
if (!controlName) return;
let control = this.myformname.controls[controlName];
//Check Formcontrol input field value
let controlValue = control.value;
// If the input field only contains "0", replace it with the input data
if (controlValue == 0 || controlValue == '') {
//Get the keypressed value
let inputData = (event as InputEvent).data;
//let numberValue = inputData.replace(/'/g, "");
if (inputData && /^d$/.test(inputData.replace(/'/g, ""))) {
//Set value of keypressed
control.setValue(inputData);
}
else{
if(controlValue == 0 && controlValue){
control.setValue(0);
}
else if(!/^d$/.test(inputData.replace(/'/g, "")) && controlValue != 0) {
control.setValue('');
}
}
}
}
onFixedAmount(FormControlName) {
let amount = this.myformname.controls[FormControlName].value;
if (amount) {
this.myformname.controls[FormControlName].setValue(amount ? Number(amount).toFixed(2) : 0);
}
}
2
Answers
I just twerked my condition a bit for else like
//Check if numput data is not numeric and also control value is not 0 so perform backspace
This will allow user to only type
numbers
, but additionally if input already containsnumeric
value and user tries to addstring
or something else thannumber
, value will be set to previus valid oneWhen User removes last number, input value will be set back to
0
.when User writes first number,
0
will be removed