繁体   English   中英

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

[英]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.

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