【Angular】angular去除输入的空格,Angular自定义属性指令-禁止input框输入空格-以及删除复制内容中的空格(附有其他解决办法)

需求:去除表单输入中的空格:包含字符串的所有(前,中,后)的空格

方法一: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

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

卸载引擎

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值