2023-09-16
Angular
00
请注意,本文编写于 821 天前,最后修改于 643 天前,其中某些信息可能已经过时。

表单组件input难免会输入空格,有时候这些空格会造成意外的事故,比如密码框如果意外在最后面加了空格,使用人又没注意,这就造成意想不到的效果。我们可以使用自定义指令在input失去焦点时自动去除前后空格,方便又省事

InputTrimDirective.ts

ts
import { 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/>
如果对你有用的话,可以打赏哦
打赏
ali pay
wechat pay

本文作者:千寻

本文链接:

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