[英]How to create angular directive text box only allow numbers space and fraction
如何為分數創建指令,以便用戶可以輸入唯一的分數,如下所示。
"10 1/2" // Valid format
"10.25" // Valid format
"10 1/2" // Invalid format extra spaces found
"dummy 12 1/2" // Invalid string format found
以下應該工作..
首先創建指令:
@Directive({
selector: '[exampleDirective]'
})
export class TestDirective {
constructor() {}
@HostListener('input', ['$event'])
ngOnChanges(evt: any) {
const pattern: RegExp = new RegExp(/^[0-9]+\.?[0-9]*$/);
if (!pattern.test(evt.target.value)) {
evt.srcElement.value = evt.srcElement.value.substring(0,evt.srcElement.value.length - 1); // this will erase the last char that does not match the pattern...
}
}
}
然后在您的輸入中選擇它
<input exampleDirective/>
你可以做這樣的事情。
1)在你的html文件中
<input type="text" (change)="onChange($event.target.value)"/>
2)在你的打字稿文件中
onChange(value) {
const reg = /[1-9][0-9]*(?:\/[1-9][0-9])*/; // -> Regex for matching only numbers and fractions
if (!reg.test(value)) { // test() matches string with regex
// reset textbox here.
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.