这可能是最好的角2-方式来阻止非数字键使用指令?
import {Directive,HostListener} from '@angular/core';
@Directive({
selector: '[blockNonNumber]'
})
export class blockNonNumberDirective {
@HostListener('keydown', ['$event']) onKeyDown(event: any) {
let keyCode = [8, 9, 37, 39, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 110];
if ( keyCode.indexOf(event.which) === -1) event.preventDefault();
}
}
我用它来允许用户只输入num,
export class blockNonNumberDirective {
constructor() { }
@HostListener('keypress') onkeypress(e){
let event = e || window.event;
if(event){
return this.isNumberKey(event);
}
}
isNumberKey(event){
let charCode = (event.which) ? event.which : event.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57)){
return false;
}
return true;
}
}
我建议使用文本遮罩组件。它非常有用。
``typescript
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { TextMaskModule } from 'angular2-text-mask';
@NgModule({
imports: [
FormsModule,
TextMaskModule
],
declarations: []
})
export class MyModule {}
```
Then, use it in your component:
```typescript
@Component({
selector: 'app',
template: `
<input [textMask]="{mask: mask}" [(ngModel)]="myModel" type="text"/>
`
})
export class AppComponent {
public myModel = ''
public mask = ['(', /[1-9]/, /d/, /d/, ')', ' ', /d/, /d/, /d/, '-', /d/, /d/, /d/, /d/]
}
```
text-mask