需求:去除表单输入中的空格:包含字符串的所有(前,中,后)的空格
方法一:angular自定义指令
禁止输入空格,即当用户按下空格键时便阻止输入,但是如果只是这样,那么用户仍然可能使用粘贴的方式输入空格,所以这里同时在keyup事件中将所有空格替换了。
import {Directive, ElementRef, HostListener, Input } from '@angular/core';import {FormGroup, FormControl, NgControl } from '@angular/forms';@Directive({selector: '[input-no-space]'})export class InputNoSpaceDirective {constructor(private elementRef: ElementRef, private control: NgControl) {}//禁止输入空格,即当用户按下空格键时便阻止输入@HostListener('keydown', ['$event'])keydownFun(evt) {if (evt.key.trim() === '') {evt.preventDefault();}}//keyup事件中将所有空格替换,避免使用粘贴的方式输入空格@HostListener('keyup', ['$event', '$event.target'])keyupFun(evt, target) {if (target.value) {this.control.control.setValue(target.value.replace(/(\s*)/g, ''));}}};
使用方法:
先引入模块:
import {InputNoSpaceDirective } from '../directive/input-no-space.directive';@NgModule({declarations: [InputNoSpaceDirective ],exports: [InputNoSpaceDirective ]})
<input type="text" [(ngModel)]="name" name="name" input-no-space />
方法二:js去除
<input οnkeyup="this.value=this.value.replace(/[, ]/g,'')"></input>
方法三:Angular中管道
管道适用于展示数据的时候使用
方法四:angular2-trim-directive
使用第三方工具
https://anein.github.io/angular2-trim-directive/
方法五:great-ngform
国产第三方工具
https://zhtt.gitee.io/angular-demo/great-ngform8/#/form/trim
【Angular】angular去除输入的空格 Angular自定义属性指令-禁止input框输入空格-以及删除复制内容中的空格(附有其他解决办法)