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