javascript - 指令不适用于非数值
问题描述
我有指令禁止在输入中输入非数字符号
这是指令
import { NgControl } from "@angular/forms";
import { HostListener, Directive } from "@angular/core";
@Directive({
exportAs: "number-directive",
selector: "number-directive, [number-directive]",
})
export class NumberDirective {
private el: NgControl;
constructor(ngControl: NgControl) {
this.el = ngControl;
}
// Listen for the input event to also handle copy and paste.
@HostListener("input", ["$event.target.value"])
onInput(value: string): void {
// Use NgControl patchValue to prevent the issue on validation
this.el.control.patchValue(value.replace(/[^0-9]/g, "").slice(0));
}
}
这是我如何使用它input
<input
type="text"
tabindex="0"
class="search__input form-control-md + {{class}}"
[value]="config.value"
[required]="config.required"
[attr.maxlength]="config.maxLength"
[attr.minLength]="config.minLength"
#inputElem
number-directive
/>
但我仍然可以写aaaaa
或任何文字
我的问题在哪里?
解决方案
怀疑有两个根本原因:
忘记
NumberDirective
declarations
添加到app.module.ts 。您需要添加
NumberDirective
到app.module.tsdeclarations
来注册指令。
@NgModule({
...
declarations: [..., NumberDirective],
})
export class AppModule {}
NgControl
您的<input>
元素没有提供者。您将收到如下错误消息,因为
[(ngModel)]
输入元素缺失。该指令期望它是一个NgControl
. 因此它需要有[(ngModel)]
.或者你需要
[formControl]="configControl"
你的<input>
元素。
错误:R3InjectorError(AppModule)[NgControl -> NgControl -> NgControl]: NullInjectorError: No provider for NgControl!
<input
type="text"
tabindex="0"
class="search__input form-control-md + {{ class }}"
[value]="config.value"
[required]="config.required"
[attr.maxlength]="config.maxLength"
[attr.minLength]="config.minLength"
#inputElem
number-directive
[(ngModel)]="config.value"
/>
或者
<input
type="text"
tabindex="0"
class="search__input form-control-md + {{ class }}"
[value]="config.value"
[required]="config.required"
[attr.maxlength]="config.maxLength"
[attr.minLength]="config.minLength"
#inputElem
number-directive
[formControl]="configControl"
/>
configControl = new FormControl();
推荐阅读
- c++ - Rcpp:加快读取大矩阵文本文件(ESRI ASCii 格式)
- r - 使用 ggplot2 包修改绘图
- angular - AWS Cloud9 与 Angular 9
- vue.js - 在 bootstrap-vue 的 b-button-group 组件中添加图标?
- sql - 如何更新表,以便只有 1 个数字为 1 的值
- svg - 如何在页面的特定部分启动 svg 滚动动画
- asp.net-mvc - MVC 在视图或控制器中查询,结果不同
- python - asyncio.gather 的顺序版本
- android - 忽略 Android 上不规则的 CSV 文件行
- rubygems - Ruby 和 Rails 中的 gem 和包有什么区别?