You need to escape for javascript and regex. For me it worked like this.
<input style="width: 65px;"
pattern="^-?[0-9]\\d*(\\.\\d+)?$"
class="form-control form-control-sm bg-light" type="number" [(ngModel)]="myProperty" required>
Since in angular html is not actual html but will be transformed to javascript so you need to escape regex special escape sequences again so that JS could understand its part of regex. If you dont escape :
html is as follows and wont work
<input style="width: 65px;" pattern="/^-?[0-9]\d*(\.\d+)?$/" class="form-control form-control-sm bg-light" type="number" [(ngModel)]="col.value" required>
In dom it is as follows
<input class="form-control form-control-sm bg-light" ng-pattern="/^-?[0-9]d*(.d+)?$/" required="" style="width: 65px;" type="number" ng-reflect-required="">
For managing a simple input like in your case you can use template ref to check validity
import { Component, ViewChild, ElementRef } from '@angular/core';
@Component({
selector: 'my-app',
template:
`<input style="width: 65px;" #ref (keyup)="trigger(ref)"
pattern="^-?[0-9]\\d*(\\.\\d+)?$"
class="form-control form-control-sm bg-light" type="number" [(ngModel)]="myProperty" required>
<h1>{{ myProperty }}</h1>`,
})
export class AppComponent {
myProperty = 222;
@ViewChild('ref') ref: ElementRef;
trigger(e) {
console.log(this.ref.nativeElement.validity.valid);
}
}
Simple version without template ref
myProperty = 22;
showError = false;
onkeydecimalCheck(e){
const value = e.target.value;
console.log(value);
var regex = new RegExp(/^-?[0-9]+(\.\d+)?$/);
const flag = regex.test(value) ;
if (!flag) {
this.showError = true;
} else {
this.showError = false;
}
}
<input style="width: 65px;" type="number" (keyup)="onkeydecimalCheck($event)"
[value]="myProperty" required>
<span *ngIf="showError">Invalid data</span>
We can display some error. The issue with number field is that if you type + at the start eventhough it displays + if you check event.target.value will be empty