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?
to avoid confusion changing model attribute name.
<input name="fruit" [(ngModel)]="fruit1" (change)="fruit1=fruit1.trim()"/>
Have you looked at https://github.com/anein/angular2-trim-directive ?
Seems like it would address your use case
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());
}
});
}