Angular: Numbers only directive

Discussão em 'Angular' iniciado por Lako12, Novembro 21, 2025.

  1. Lako12

    Lako12 Guest

    I have this piece of code

    <input matInput type="number" [(ngModel)]="value"
    (ngModelChange)="onChange(true)" />


    But I want to be able to enter only numbers, not other characters like + , . -

    I found this directive https://stackblitz.com/edit/angular-numbers-only-directive?file=app/app.component.ts

    The problem is that the onChange method is called even if I enter an invalid value. I don't want to put the same condition in the onChange method; I want to be able to modify the directive to emit the event or not. So it should only work if it's actually a number. I found some solutions with keyPress, but it is deprecated. I am using angular 19

    Continue reading...

Compartilhe esta Página