Tomada de entrada de texto só aceitar valores percentuais pode ser um pouco complicado, aqui está uma maneira de fazer que, ao eliminar os não valores numéricos e a adição de ' %' no final.
sinta-se livre para compartilhar suas ideias!
Tomada de entrada de texto só aceitar valores percentuais pode ser um pouco complicado, aqui está uma maneira de fazer que, ao eliminar os não valores numéricos e a adição de ' %' no final.
sinta-se livre para compartilhar suas ideias!
a fim de tornar a entrada de texto aceitam números de float e adicione "%" no final:
<input id="id" type="text" formControlName="percentControl" (focusin)="start($event)"(focusout)="end($event)" />
end(e) {
// console.log(/^[0-9.]*$/.test(e.target.value));
if(!/^[0-9.]*$/.test(e.target.value))
e.target.value = e.target.value.replaceAll(/[^0-9.]/g, '').trim();
//add ' %' at the end
if(e.target.value.length)
e.target.value = e.target.value+ ' %';
//this part is needed when working with angular form validation (ngForm required
//or formGroup Validators.required), else null value won't trigger the validation
else
e.target.value = '0 %';
}
start(e) {
e.target.value = e.target.value.replace('%', '').trim();
}
//make sure to get rid from ' %' when posting data to the backend
//example with formControl
// the + is for converting string to number
dataToPost = +this.form.get('percentControl').value.replaceAll('%', '');
//Use Angular percent pipe
local: string = "en-US";
percentPipe:PercentPipe = new PercentPipe(this.local);
myVariable = this.percentPipe.transform(dataFromBackEnd/100);