简体   繁体   English

如何创建角度指令文本框只允许数字空格和分数

[英]How to create angular directive text box only allow numbers space and fraction

How to create a directive for fraction number so a user can enter the only fraction number just like below.如何为分数创建指令,以便用户可以输入唯一的分数,如下所示。

"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

The following should work..以下应该工作..

first create the directive:首先创建指令:

@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...
  }
 }
}

and then select it in your input然后在您的输入中选择它

<input exampleDirective/>

You can do something like this.你可以做这样的事情。

1) In your html file 1)在你的html文件中

<input type="text" (change)="onChange($event.target.value)"/>

2) In your typescript file 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM