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

misterGrosar picture misterGrosar · Apr 13, 2017 · Viewed 26.8k times · Source

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?

Answer

user6534517 picture user6534517 · Jun 4, 2018

to avoid confusion changing model attribute name.

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