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
JavaScript
x
2
1
<input type="number" (keyup)="numbersOnly($event)" placeholder="0000000000" formControlName="phone" maxlength="10"/>
2
Above works to call this function in the component but it is not working to prevent letters.
JavaScript
1
8
1
numbersOnly(val) {
2
let y = this.trackerForm.controls['phone'].value
3
y.value = y.value.replace(/[^0-9.-]/g, '');
4
5
console.log('y', y);
6
7
}
8
- 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
.
JavaScript
1
5
1
let y = this.trackerForm.controls['phone'];
2
this.trackerForm.controls['phone'].patchValue(y.value.replace(/[^0-9.-]/g, ''));
3
// OR
4
this.trackerForm.controls['phone'].setValue(y.value.replace(/[^0-9.-]/g, ''));
5
Refer demo.