current position:Home>[angular] angular removes the input spaces. The angular user-defined attribute instruction - prohibits the input box from entering spaces - and deletes the spaces in the copied content (with other solutions attached)

[angular] angular removes the input spaces. The angular user-defined attribute instruction - prohibits the input box from entering spaces - and deletes the spaces in the copied content (with other solutions attached)

2022-06-24 09:14:46Uninstall engine

demand : Remove spaces from form input : Contains all of the string ( front , in , after ) Space for

Method 1 :angular Custom instruction

No spaces , That is, when the user presses the spacebar, the input is blocked , But if it's just like this , Then the user may still use the paste method to enter a space , So here at the same time keyup Event with all spaces replaced .

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) {
    
  }

  // No spaces , That is, when the user presses the spacebar, the input is blocked 
  @HostListener('keydown', ['$event'])
  keydownFun(evt) {
    
    if (evt.key.trim() === '') {
    
      evt.preventDefault();
    }
  }

  //keyup Replace all spaces in the event , Avoid using paste to enter spaces 
  @HostListener('keyup', ['$event', '$event.target'])
  keyupFun(evt, target) {
    
    if (target.value) {
    
      this.control.control.setValue(target.value.replace(/(\s*)/g, ''));
    }
  }
};

Usage method :
First, introduce the module :

import {
     InputNoSpaceDirective } from '../directive/input-no-space.directive';
@NgModule({
    
	declarations: [InputNoSpaceDirective ],
	exports: [InputNoSpaceDirective ]
})

<input type="text" [(ngModel)]="name" name="name" input-no-space />

Method 2 :js Remove

<input οnkeyup="this.value=this.value.replace(/[, ]/g,'')"></input>

Method 3 :Angular Middle pipe

Pipeline is suitable for displaying data

Method four :angular2-trim-directive

Using third-party tools

https://anein.github.io/angular2-trim-directive/

Method five :great-ngform

Domestic third-party tools

https://zhtt.gitee.io/angular-demo/great-ngform8/#/form/trim

copyright notice
author[Uninstall engine],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2022/175/202206240757123840.html

Random recommended