我已经从https://www.davebennett.tech/angular-4-input-numbers-directive/创建了一个指令,这样我就可以限制用户只输入电话号码中的数字。在src/app/app.sharerd.module.ts
文件中,我执行了以下代码来导入指令:
import { NumberOnlyDirective } from './number.directive';
declarations: [..., ..., NumberOnlyDirective], ...
export class SharedModule { }
现在,我已经在/src/
文件夹下创建了名为modules/auth/component/
的文件夹。
在/src/auth/
文件夹中的auth.module.ts
下,我完成了以下操作:
import { NgModule } from '@angular/core';
import { SharedModule } from '../../app/app.shared.module';
...
...
现在,在/src/auth/component/
下的signup.html
中
<input type="text" name="phone" myNumberOnly ... > ...
...
我仍然可以在文本框中输入字符/特殊字符等,但是,我在console/cli中没有看到任何错误。
发布于 2019-01-17 19:52:22
当您在共享模块中使用自定义指令/管道时,您还需要将其导出。
基本上,在您的教程中,他创建了指令并在app模块中声明了它。但在您的示例中,您将指令放在一个共享模块中,因此您需要将指令放在声明括号中,同时也放在导出中。
shared.module.ts:
@NgModule({
/* ... */
declarations: [YourDirective],
exports: [YourDirective]
/* ... */
})
发布于 2020-11-30 07:22:55
三个快速指令调试技巧:
debugger;
语句放入指令的构造函数中。这样,您就可以确定它何时工作,并且可以将其删除。selector: '[magicFeature]'
,而不是ng serve
。您需要重新启动您的ng serve
,以确保所有内容都已刷新。发布于 2020-11-30 12:06:39
试试这个:
import { Directive, ElementRef, HostListener, Input } from '@angular/core';
import { NgControl } from '@angular/forms';
@Directive({
selector: 'input[type=number], input[numbersOnly]'
})
export class NumbersOnlyInputDirective {
constructor(private elRef: ElementRef) { }
@HostListener('input', ['$event']) onInputChange(event) {
const initalValue = this.elRef.nativeElement.value;
this.elRef.nativeElement.value = initalValue.replace(/[^0-9]*/g, '');
if ( initalValue !== this.elRef.nativeElement.value) {
event.stopPropagation();
}
}
}
https://stackoverflow.com/questions/54234597
复制相似问题