79098644

Date: 2024-10-17 14:56:38
Score: 0.5
Natty:
Report link

Thanks all for your comments. I'm gonna use part of your answers.

I get further in the code, and the component I'm using is a component from echarts and echarts is using both string and number for numbers.

Thus, I need to get them both string in the form, check the value, and if necessary cast it to number when I apply the form to the component. Finally, I'll have to do it.

Still, I'm using directive like this, and I'll improve it for decimal and negative values:

import { Directive, ElementRef, HostListener } from '@angular/core';
import { NgControl } from '@angular/forms';

@Directive({
  selector: '[appInputNumber]'
})
export class NumberDirective {

  /**
   * Constructeur
   */
  constructor(private el: ElementRef, private control: NgControl) {}

  /**
   * Ecoute de l'évènement de modification d'input
   */
  @HostListener('input', ['$event']) onInputChange($event: KeyboardEvent) {
    const input = this.el.nativeElement as HTMLInputElement;
    let sanitizedValue = input.value.replace(/[^0-9]/g, '');
    if (sanitizedValue === '') {
      sanitizedValue = null;
    }

    if (this.control && this.control.control?.value !== sanitizedValue) {
      this.control.control?.setValue(sanitizedValue);
    }
  }
}
Reasons:
  • Blacklisted phrase (0.5): Thanks
  • Blacklisted phrase (0.5): I need
  • Long answer (-1):
  • Has code block (-0.5):
  • Self-answer (0.5):
  • Low reputation (0.5):
Posted by: Manuela CodingPadawan