angular2-trim-directive
angular2-trim-directive copied to clipboard
Cannot disable trim dynamically
It would be great if there was an option to turn the trim directive on/off (that can be bound to some variable). I tried setting [trim]="something-that-is-not-an-event", for example [trim]="disabled", and this would nearly work save for a small glitch in updateValue:
private updateValue(event: string, value: string): void {
// check if the user has set an optional attribute, and Trimmmm!!! Uhahahaha!
value = this.trim !== "" && event !== this.trim ? value : value.trim();
const previous = this._value;
// write value to the element.
this.writeValue(value);
// ...
if ((this._value || previous) && this._value.trim() !== previous) {
this.onChange(this._value);
}
}
When this.trim doesn't match an event, the value is not trimmed and writeValue is called with the actual value (OK). But the onChange is propagated when this._value.trim() !== previous. This assumes the value has always been trimmed, which is not the case according to the "Uhahaha" line at the beginning of the function :).
So what happens when I type "1" then "space" with trimming disabled, writeValue will write the "1" but for the space, it will not propagate onChange because "1 ".trim() does equal previous.
I think what you want here is:
if ((this._value || previous) && this._value !== previous) {
this.onChange(this._value);
}
This will propagate the change whenever the value actually changes, regardless of whether the value was trimmed or not.