Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

268
Visualizações
Angular 2 Salto de cursor al final del cuadro de texto al cambiar datos

Hay algunas restricciones en el campo de nombre, por lo que estoy tratando de validar el campo de nombre usando la directiva como se muestra a continuación. Dentro de la directiva, estoy usando una expresión regular para verificar el nombre válido y luego reemplazando el nombre válido en el cuadro de texto usando valueAccessor.writeValue(newVal)

Aquí el problema es cuando estoy tratando de escribir en medio de alguna palabra en el salto del cursor del cuadro de texto al final.

 @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); } }
about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

Eso viene del hecho de DefaultValueAccessor escribe a ciegas el valor del elemento, si hay un foco o no, selección o no. Tuve que lidiar con ese comportamiento yo mismo, ya que estaba usando un formulario que se guardaba automáticamente y tuve que anular DefaultValueAccessor y crear uno que solo escribiera valor si fuera diferente (no creo que funcione para usted , vea abajo) :

 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); } }

Para su caso, es posible que deba lidiar con la selección de entrada:

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

Tenga en cuenta que puede que no sea preciso ya que está modificando la entrada...

about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda