In my Angular 4 application I have this input box in which I ONLY want numbers… 0-9 to be entered.. otherwise I want it to clear out onkeyup
HTML
<input type="number" (keyup)="numbersOnly($event)" placeholder="0000000000" formControlName="phone" maxlength="10"/>
Above works to call this function in the component but it is not working to prevent letters.
numbersOnly(val) { let y = this.trackerForm.controls['phone'].value y.value = y.value.replace(/[^0-9.-]/g, ''); console.log('y', y); }
- Is .value the wrong approach?
- Should I be using event preventdefault?
The console log for ‘y’ shows correctly.
What do I need to do?
Advertisement
Answer
Since you are using ReactiveForm, you should understand that FormConrtol’s value only has a getter
.
If you want to change formControl’s value, use patchValue
or setValue
.
let y = this.trackerForm.controls['phone']; this.trackerForm.controls['phone'].patchValue(y.value.replace(/[^0-9.-]/g, '')); // OR this.trackerForm.controls['phone'].setValue(y.value.replace(/[^0-9.-]/g, ''));
Refer demo.