-
Notifications
You must be signed in to change notification settings - Fork 19
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
doesn't work when an input has [readonly]="condition" data-binding #15
Comments
I have the same problem. @KingMario Did you find a workaround? |
If others are interested in a workaround, I respond to my own question: My current implementation of this directive: @Directive({
providers: [{
multi: true,
provide: NG_VALUE_ACCESSOR,
useExisting: TrimDirective,
}],
selector: "[trim]",
})
export class TrimDirective extends DefaultValueAccessor implements AfterViewInit {
private afterViewInit = false;
constructor(
renderer: Renderer2,
private elementRef: ElementRef,
@Optional() @Inject(COMPOSITION_BUFFER_MODE) compositionMode: boolean,
) {
super(renderer, elementRef, compositionMode);
}
ngAfterViewInit(): void {
this.afterViewInit = true;
}
@HostListener("input", ["$event.target.value"])
onInput(value: string): void {
this.onChange(this.trimIfNeeded(value));
}
@HostListener("blur", ["$event.target.value"])
onBlur(value: string): void {
this.writeValue(value);
}
// tslint:disable-next-line:no-any
writeValue(value: any): void {
super.writeValue(this.trimIfNeeded(value));
}
private trimIfNeeded(value: string): string {
return this.needsTrim() ? value.trim() : value;
}
private needsTrim(): boolean {
// wait for property binding
if (!this.afterViewInit) {
return false;
}
const inputElement: HTMLInputElement = this.elementRef.nativeElement;
return !inputElement.readOnly && ["checkbox", "radio", "password"].indexOf(inputElement.type) < 0;
}
} |
@stenzengel just my two cents: https://www.npmjs.com/package/ngx-trim-directive |
@KingMario Thanks. |
@stenzengel well, it's in a different way actually. The directive just sends an input event after trimming the value of the element so that the model will be updated by the ValueAccessor behind, whichever it is. The disadvantage of the directive is that, if the user binds a callback to the input event, the callback will be called twice on each of user's keystrokes. Why is another directive? @stenzengel Thanks for you comment on my issue and if it's possible, you may fix it by submitting your codes and raising a pull request to this repo, so that this issue and discussion can be closed. |
Even if readonly is removed by angular data-binding, the accessor doesn't work.
The text was updated successfully, but these errors were encountered: