表单组件input难免会输入空格,有时候这些空格会造成意外的事故,比如密码框如果意外在最后面加了空格,使用人又没注意,这就造成意想不到的效果。我们可以使用自定义指令在input失去焦点时自动去除前后空格,方便又省事
InputTrimDirective.ts
tsimport { Directive, ElementRef, HostListener } from '@angular/core';
import { NgControl } from '@angular/forms';
@Directive({
selector: '[input-trim]'
})
export class InputTrimDirective {
constructor(el: ElementRef, private control: NgControl) {
}
@HostListener('blur', ['$event','$event.target'])
blurFun(event: any,target:any) {
//this.control.control?.setValue(this.el.value.replace(/(^\s*)|(\s*$)/g, ''));
if (target.value) {
if (this.control) {
this.control.control?.patchValue(target.value.replace(/(^\s*)|(\s*$)/g, ''));
this.control.control?.updateValueAndValidity();
}
else {
this.el.nativeElement.value = target.value.replace(/(^\s*)|(\s*$)/g, '');
}
}
}
}
使用
html<input [(ngModel)]="form.password" type="password" input-trim/>


本文作者:千寻
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!