在Angular中,可以使用自定义指令来限制文本框只能输入整数。下面是一个实现这一功能的示例代码:
import { Directive, ElementRef, HostListener } from '@angular/core';
@Directive({
selector: '[numberOnly]'
})
export class NumberOnlyDirective {
constructor(private el: ElementRef) {}
@HostListener('input', ['$event']) onInputChange(event) {
const initialValue = this.el.nativeElement.value;
this.el.nativeElement.value = initialValue.replace(/[^0-9]*/g, '');
if ( initialValue !== this.el.nativeElement.value) {
event.stopPropagation();
}
}
}
import { NumberOnlyDirective } from './number-only.directive';
@NgModule({
declarations: [
NumberOnlyDirective
],
...
})
export class AppModule { }
现在,文本框将只允许输入整数。任何其他非数字字符都将被自动删除。