[Angular Directive] 输入框禁止为空字符串与自动去除空格指令
一、前言input 输入框自带了 在使用自定义的 Directive 修改 input 输入框值或属性时,需要注意:
二、实例
1. 验证空字符串通过添加自定义的 import { Directive,ElementRef,HostListener,Input,Renderer } from '@angular/core';
import { FormGroup,FormControl,NgControl } from '@angular/forms';
@Directive({
selector: '[input-required]'
})
export class InputRequiredDirective {
constructor(private elementRef: ElementRef,private control : NgControl) {
if (control && control.control) {
control.control.setValidators((c: FormControl) => {
let v = c.value;
if (!v || v.trim() == '') {
return {'required': true};
}
return null;
});
}
}
}
使用方式<input type="text" [(ngModel)]="name" name="name" input-required />
2. 替换左边空格替换左边空格,其实也意味可以在字符串右侧输入空格,却无法全输入空格,但是这种方法有一个缺陷,即如果一直按住空格,然后点击表单的提交,也能绕过输入框的 同时请注意,这里使用 import { Directive,NgControl } from '@angular/forms';
@Directive({
selector: '[input-ltrim]'
})
export class InputLeftTrimDirective {
constructor(private elementRef: ElementRef,private control : NgControl) {
}
@HostListener("keyup",["$event","$event.target"])
keyupFun(evt,target) {
if (target.value) {
this.control.control.setValue(this.ltrim(target.value));
}
}
ltrim(str) {
return str.replace(/(^s*)/g,"");
}
}
使用方式<input type="text" [(ngModel)]="name" name="name" input-ltrim />
3. 禁止输入空格禁止输入空格,即当用户按下空格键时便阻止输入,但是如果只是这样,那么用户仍然可能使用粘贴的方式输入空格,所以这里同时在 import { Directive,Input } from '@angular/core';
import { FormGroup,NgControl } from '@angular/forms';
@Directive({
selector: '[input-noSpace]'
})
export class InputNoSpaceDirective {
constructor(private elementRef: ElementRef,private control : NgControl) {
}
@HostListener("keydown",["$event"])
keydownFun(evt) {
if (evt.key.trim() == '') {
evt.preventDefault();
}
}
@HostListener("keyup",target) {
if (target.value) {
this.control.control.setValue(target.value.replace(/(s*)/g,""));
}
}
}
使用方式<input type="text" [(ngModel)]="name" name="name" input-noSpace />
二、配置上面省略了配置,这里一并贴出。 1. 在 import { InputLeftTrimDirective } from './input-trim/input-ltrim.directive'
import { InputNoSpaceDirective } from './input-trim/input-noSpace.directive'
import { InputRequiredDirective } from './input-required/input-required.directive'
export const DIRECTIVES : Array<any> =[
InputLeftTrimDirective,InputNoSpaceDirective,InputRequiredDirective,]
2. 在 import { DIRECTIVES } from './directives';
@NgModule({
declarations: [
..._DIRECTIVES,],}
三、参考链接
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |