使用angular的自定义指令解决输入框不可以输入空格的问题
1.在开发中有很多的数据框,输入空格是没有意义的,我们一般会不允许使用者输入空格
对于一般的使用输入框的地方一般为表单和搜索,这里有两种解决方案,
1.自定义表单验证和输入框验证;
2.使用自定义指令的方式来解决问题;
自定义表单验证和输入框验证已经使用过了,这次使用Directive来解决问题
1.新建指令文件(input-not-null.directive.ts)
import { Directive, HostListener } from '@angular/core';import { NgControl } from '@angular/forms';@Directive({selector: '[appInputNotNull]'})export class InputNotNullDirective {constructor(private $control: NgControl) {}@HostBinding('style.borderColor') borderColor: string;// 监听元素的keydown事件@HostListener('keydown', ['$event'])keydown(event) {if (event.key.trim() === '') {// 取消事件的默认动作event.preventDefault();// this.borderColor = 'red';} else {this.borderColor = '#d6d6d6'; // 不为空时输入框的颜色}}// 监听元素的keyup事件@HostListener('keyup', ['$event', '$event.target'])keyup(target) {if (target.value) {this.$control.control.setValue(this.trim(target.value));}}// 正则当输入空格时,将输入的值清空trim(inputStr) {return inputStr.replace(/(^\s*)/g, '');}}
2 在使用的module中引入
declarations: [InputNotNullDirective] // 在模块下的所有需要去空格的组件都可以应用了
3.组件中使用
<textarea formControlName="ReMark" placeholder="请输入备注信息" appInputNotNull></textarea>
4 测试
这样在输入框中就无法输入空格了!
5总结
@Directive ------ 自定义指令@HostListener ------ 监听宿主元素的事件(使用该指令的元素的事件)NgControl ------控制器@HostBinding ------ 监听宿主元素的属性,可以为宿主元素实时添加属性,如:类,样式,属性等(可以跟@HostListener一起用,比如输入空格的时候,输入框会变红等等)