创建一个ts文件,并在module.ts中定义
import { Directive, ElementRef, HostListener, Input } from '@angular/core';
import { FormGroup, FormControl, NgControl } from '@angular/forms';
@Directive({selector: '[input-noSpace]'})
export class NoSpace {constructor(private elementRef: ElementRef, private control : NgControl) {}@HostListener("keydown", ["$event"])keydownFun(evt) { if (evt.key.trim() == '') {evt.preventDefault();}}@HostListener("keyup", ["$event", "$event.target"])keyupFun(evt, target) { if (target.value) {this.control.control.setValue(target.value.replace(/(\s*)/g, ""));}}
}
然后直接在input框中加入属性input-noSpace就可以使用了
(注意input框要绑定ngmodel)
<input type="test" name="managerNo" id="managerNo" [(ngModel)]="info.managerNo" required#idClass="ngModel" (keyup)="doCode()" maxlength="50" input-noSpace/></td>