I have a input field where requirement is that it has 0 intially 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 arrises 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 add 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 non numberic value it makes my number set ” and also on bacspace keypress it should allow backspace and remove zero but should not give error 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);
}
}
Paras Panchal is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.