Search code examples
angularjsangular-ngmodel

Can a number input in Angular begin with a null value?


What is the correct way to have an Angular number input begin with a null value, and only have a value if the user enters one?

I have a <input type="number" ng-model="myNumber"> in Angular. I want to initialize myNumber with a null value so it only has a value if the user enters one: $scope.myNumber = null;. However a null value causes the error Error: [ngModel:numfmt].


Solution

  • It is a logical error to define the default value of null for number type. As explained here,

    The number input directive requires the model to be a number.

    Please refer the example here to use string to convert the string to number directive, using ngModel.$parsers and ngModel.$formatters in which case having null will also suffice