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

Issue

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?

Solution

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

Seems like it would address your use case

Answered By – Vijay

Answer Checked By – Marilyn (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.