在Angular 2中阻止非数字指令

时间:2016-10-30 09:59:17

标签: angular event-handling angular-directive

这可能是使用指令阻止非数字键的最佳角度双向方式吗?

data

2 个答案:

答案 0 :(得分:4)

我使用它来允许用户只输入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;
  }
}

答案 1 :(得分:1)

我建议使用text-mask组件。它非常有用。

``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