输入类型上的自定义行为=“编号” [角]
使用Firefox,用户可以将字母输入到<输入类型=“ number”/>
。我通过使用自定义指令来阻止此功能,该指令仅启用字符 [0-9] 。
import { Directive, ElementRef, HostListener } from '@angular/core';
@Directive({
selector: '[appOnlyNumber]',
})
export class OnlyNumberDirective {
readonly acceptedKeys = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
@HostListener('keydown', ['$event']) down(e: any) {
if (!this.acceptedKeys.includes(e.key)) {
e.preventDefault();
}
}
constructor(private er: ElementRef) {}
}
但是,现在我们的编码器需要记住在创建数字输入时始终包含此指令。我希望这个过程是万无一失的,因此永远不会忘记。
有没有办法至少警告程序员他忘记添加此指令? 就像在构建后检查DOM,并且在包含输入号时(但不是指令)时,与在控制台中发送警告一样?
还是我可以覆盖默认输入html元素的功能,以使此密钥预防(仅0-9)默认情况下?
Using Firefox, the user can input letters to an <input type="number"/>
. I prevented this with using a custom directive, which only enables characters [0-9].
import { Directive, ElementRef, HostListener } from '@angular/core';
@Directive({
selector: '[appOnlyNumber]',
})
export class OnlyNumberDirective {
readonly acceptedKeys = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
@HostListener('keydown', ['$event']) down(e: any) {
if (!this.acceptedKeys.includes(e.key)) {
e.preventDefault();
}
}
constructor(private er: ElementRef) {}
}
However now our coders need to remember to always include this directive, when creating a number input. I want this process to be foolproof, so it is never forgot.
Is there a way to at least warn the programmer that he forget to add this directive?
Like checking the DOM after build, and when it contains an input number, but not the directive, than send a warning in the console?
Or can I override the functionality of the default input HTML element, to have this key prevention (0-9 only) by default?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在指令中使用属性选择器:
Use an attribute selector in the directive: