Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

403
Vistas
"Trim" directive for angular 2 and reflect changes to ngModel

I want to create Angular 2 directive that will tirm spaces only from begining and the end of the text that user has typed into input field.

I have input field

<input trim name="fruit" [(ngModel)]="fruit"/>

and directive

import {Directive, ElementRef} from "@angular/core";

@Directive({
  selector: 'input[trim]',
  host: {'(blur)': 'onChange($event)'}
})

export class TrimWhiteSpace {

  constructor(private cdRef:ChangeDetectorRef, private el: ElementRef){}

  onChange($event:any) {
    let theEvent = $event || window.event;
    theEvent.target.value = theEvent.target.value.trim();
  }
}

which works fine, removes spaces and changes text in input field, but the problem is that the value in ngModel variable "fruit" is not changed and it still contains text with spaces at the begining or at the end.

I also tried to add following to onChange method

this.el.nativeElement.value = theEvent.trim();
this.cdRef.detectChanges();

and change form (blur) to (ngModelChange), but text in ngModel is not effected.

Any suggestions?

about 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

to avoid confusion changing model attribute name.

<input name="fruit" [(ngModel)]="fruit1" (change)="fruit1=fruit1.trim()"/>
about 4 years ago · Santiago Trujillo Denunciar

0

Have you looked at https://github.com/anein/angular2-trim-directive ?

Seems like it would address your use case

about 4 years ago · Santiago Trujillo Denunciar

0

CommonController in example is just base class that triggers subject in onDestroy hook to unsubsribe from observable.

@Directive({
  selector: '[appTrimOnBlur]'
})
export class TrimOnBlurDirective extends CommonController implements OnInit {

  constructor(private elementRef: ElementRef,
              @Self() private ngControl: NgControl) {
    super();
  }

  ngOnInit(): void {
    fromEvent(this.elementRef.nativeElement, 'blur').pipe(
      takeUntil(this.unsubscribeOnDestroy)
    ).subscribe(() => {
      const currentValue: string = this.ngControl.value.toString();
      const whitespace: string = ' ';
      if (currentValue.startsWith(whitespace) || currentValue.endsWith(whitespace)) {
        this.ngControl.control.patchValue(currentValue.trim());
      }
    });
  }

}

You can create generic trim directive, that will make trim not only for blur event,but for any, that you will provide:

@Input() public trimEventName: string = 'blur';

  constructor(private elementRef: ElementRef,
              @Self() private ngControl: NgControl) {
    super();
  }

  ngOnInit(): void {
    fromEvent(this.elementRef.nativeElement, this.trimEventName).pipe(
      takeUntil(this.unsubscribeOnDestroy)
    ).subscribe(() => {
      const currentValue: string = this.ngControl.value.toString();
      const whitespace: string = ' ';
      if (currentValue.startsWith(whitespace) || currentValue.endsWith(whitespace)) {
        this.ngControl.control.patchValue(currentValue.trim());
      }
    });
  }
about 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda