1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

Angular/ Reactive form / Input - Handle typeof input.value for numeric value

Discussão em 'Angular' iniciado por Manuela CodingPadawan, Outubro 17, 2024 às 09:43.

  1. I use Ng 14 and Reactive Forms.I want to have a input field accepting only numbers, but I want it to be customizable accepting or not positive/negative values, or decimal values.

    The main solution I see, is to use a directive like it is described here for example: Angular2 - Input Field To Accept Only Numbers

    However, on this, I have two questions:

    1. About directive itself. If I use this kind of writing, then it's accessible from all the app. Isn't it an issue? It looks strange to me.

    <input formControlName="myNumber" appNumericInput [allowNegative]="true" [allowDecimal]="true">


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

    @Directive({
    selector: '[appNumericInput]'
    })
    export class NumericInputDirective {
    @Input() allowNegative: boolean = false; // Allow negative values
    @Input() allowDecimal: boolean = false; // Allow decimal values

    // Here the code to sanitize myNumber

    }

    1. Using a simple input field, and formControl, the value is considered as a string. Then, when I use my value to set my object, this is passed as a string. Is there a way to have the control to return a numeric value? Here, it is a simple case. I can have complex objects so I wouldn't cast value by value.

    const formValues = this.componentForm.value;

    this.component.myNumber = formValues.myNumber;

    Continue reading...

Compartilhe esta Página