Angular 2 Move cursor at end of text field when data changes

There are some restrictions on the name field, so I'm trying to check the name field using a directive, as shown below. Inside the directive, I use a regular expression to validate the correct name, and then replace the real name with a text box usingvalueAccessor.writeValue(newVal)

The problem here is when I try to type the middle of some word in the cursor cursor at the end of the window.

@Directive({
    selector: '[validateName]',
    host: {
        '(ngModelChange)': 'onInputChange($event, false)',
        '(keydown.backspace)': 'onInputChange($event.target.value, true)',
        '(focusout)': 'removeClass()'
    }
})

export class NameValidator {

    constructor(public model: NgControl,public renderer: Renderer, public el: ElementRef) { }

    onInputChange(event, backspace) {
        if (!backspace) {
            // Remove invalid characters (keep only valid characters)
            var newVal = event.replace(/^[0-9\s]/g, '').replace(/[^A-Za-z0-9_$]/g,'');

            // Add class for invalid name. 
            if (/^[0-9\s]/g.test(event) || /[^A-Za-z0-9_$]/g.test(event)) {
                this.renderer.setElementClass(this.el.nativeElement, 'invalid-name', true);
            }
            else {
                this.renderer.setElementClass(this.el.nativeElement, 'invalid-name', false);
            }
            // set the new value
            this.model.valueAccessor.writeValue(newVal);
        }
    }
    removeClass() {
        this.renderer.setElementClass(this.el.nativeElement, 'invalid-name', false);
    }
}
+8
source share
2 answers

- , DefaultValueAccessor , , . , , , DefaultValueAccessor , , ( , , . ):

export const DEFAULT_VALUE_ACCESSOR: any = {
    provide: NG_VALUE_ACCESSOR,
    useExisting: forwardRef(() => DefaultValueAccessor),
    multi: true
};

@Directive({
    selector: "input:not([type=checkbox])[formControlName],textarea[formControlName],input:not([type=checkbox])[formControl],textarea[formControl],input:not([type=checkbox])[ngModel],textarea[ngModel],[ngDefaultControl]",
    host: {"(input)": "onChange($event.target.value)", "(blur)": "onTouched()"},
    providers: [DEFAULT_VALUE_ACCESSOR]
})
export class DefaultValueAccessor implements ControlValueAccessor {
    onChange = (_: any) => {
    };
    onTouched = () => {
    };

    constructor(private _renderer: Renderer, private _elementRef: ElementRef) {
    }

    writeValue(value: any): void {
        const normalizedValue = value == null ? "" : value;
        // line bellow is the only line I added to the original one
        if ((this._elementRef.nativeElement as HTMLInputElement).value !== normalizedValue) 
            this._renderer.setElementProperty(this._elementRef.nativeElement, "value", normalizedValue);
    }

    registerOnChange(fn: (_: any) => void): void {
        this.onChange = fn;
    }

    registerOnTouched(fn: () => void): void {
        this.onTouched = fn;
    }

    setDisabledState(isDisabled: boolean): void {
        this._renderer.setElementProperty(this._elementRef.nativeElement, "disabled", isDisabled);
    }
}

:

let start=this.el.nativeElement.selectionStart;
let end = this.el.nativeElement.selectionEnd;
this.model.valueAccessor.writeValue(newVal);
this.el.nativeElement.setSelectionRange(start,end);

, , ...

+3

Angular Material, matInput, "" .

:

 // ... wait 10 seconds
 this.form.patchValue({ firstName: 'John', lastName: 'Smith'});

 // ... wait 10 seconds
 this.form.patchValue({ firstName: 'Sarah', lastName: 'Jones'});

firstName , John Sarah , Jo|hn, , Smith .

, , Sarah| , Sarah .

, , :-) !

0

Source: https://habr.com/ru/post/1016623/


All Articles