如何为分数创建指令,以便用户可以输入唯一的分数,如下所示。
"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/>
关于javascript - 如何创建 Angular Directive(指令)文本框只允许数字空格和分数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55467416/