Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

293
Views
Angular Cómo formatear valores reactivos de FormControls después de invocar el valor de parche en ngOnInit

Quiero dar formato a campos de entrada específicos cuando el formulario se actualice por primera vez con la respuesta inicial, pero no sé cómo hacer el formato inicial.

El siguiente ejemplo es un intento en el que traté de escuchar ngModelChange . Esto crea un bucle infinito si establece Valor en FormControl o la entrada no tomará valores, pero transmite la idea de que me gustaría actualizar el formato después de que el componente principal reciba la respuesta inicial. A continuación, se muestra cómo manejo el formateo después usando eventos de usuario, lo que funciona.

 import { Directive, HostListener, ElementRef } from '@angular/core'; import { DecimalPipe } from '@angular/common'; import { FormGroup, NgControl } from '@angular/forms'; @Directive({ selector: '[cfFloat]', providers: [DecimalPipe] }) export class FloatDirective { public element: HTMLInputElement; constructor( private elementRef: ElementRef, private decimalPipe: DecimalPipe, private ngControl: NgControl ) { this.element = this.elementRef.nativeElement; } // ISSUE: this is not the proper event to listen to for a single // initial formatting of any field with this directive, but I // can't figure out how you would do the equivalent to this??? @HostListener('ngModelChange', ['$event']) onModelChange(event: Event) { let value = this.element.value.replace(/[^\d\.]+/g, ''); value = this.decimalPipe.transform(value, '1.2-2'); //this.ngControl.control.setValue(value); // infinite loop, blows stack this.element.value = value; // prevents changes from being made } @HostListener('blur', ['$event']) onBlur(event: KeyboardEvent) { let value = this.element.value.replace(/[^\d\.]+/g, ''); value = this.decimalPipe.transform(value, '1.2-2'); this.element.value = value; // format for user, but don't change model } @HostListener('focus', ['$event']) onFocus(event: KeyboardEvent) { const input = event.target as HTMLInputElement; input.value = this.trim(input.value); // format for user, but don't change model } }

En este momento, la única forma en que puedo pensar en hacer algo como esto es recorrer todas las entradas en la página para forzar el enfoque, hacer que se formatee y luego configurar el formulario para que no se toque nuevamente, lo cual es una solución horrible.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Terminé usando valueChanges en NgControl y luego cancelé la suscripción después de recibir la respuesta inicial de los formularios. No hizo clic hasta que en VSCode mostró que valueChanges era un Observable.

 public ngOnInit() { const handle = this.ngControl.valueChanges .subscribe((value: string) => { this.element.value = this.decimalPipe.transform(value, '1.2-2'); handle.unsubscribe(); }); }
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!