Zmusić wprowadzanie tekstu przyjmować tylko wartości procentowe może być nieco trudniejsze, oto sposób, aby to zrobić, usuwając jeśli nie podano wartości i dodając " % " na końcu.
zapraszam do dzielenia się swoimi pomysłami!
Zmusić wprowadzanie tekstu przyjmować tylko wartości procentowe może być nieco trudniejsze, oto sposób, aby to zrobić, usuwając jeśli nie podano wartości i dodając " % " na końcu.
zapraszam do dzielenia się swoimi pomysłami!
aby wprowadzić tekst, zapoznać się z liczb zmiennoprzecinkowych i dodaj "%" na końcu:
<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);