; last updated - 2 minutes read

I found an interesting search keyword in the visitor statistics: ng-type. Looking at the AngularJS doc, you'll never find ng-type. Every input field they show uses the plain old HTML attribute type.

Introducing ng-type adds the option to change an input field's data type dynamically. Why hasn't ng-type been added to Angular?

One reason is you hardly ever need dynamic types in input fields. I know a couple of applications of dynamic types, but they are very exotic.

The other, more important reason is compatibility with Internet Explorer. Until IE8, the type of an input field could not be changed. So as long as AngularJS aims at IE8 compatibility, there won't be an ng-type. Luckily, AngularJS 1.3 and AngularJS 2.0 dropped support for IE8, so the rules of the game have changed.

If you need to change the type of an input field, there are several options:

  • Add a hidden field for each type. Only the field you currently need is displayed.
  • Manipulate the DOM. However, that's difficult with AngularJS (you have call the compiler after the modification. Maybe you even have to destroy the scope before). You also have to copy every attribute. Alternatively, you can use this fiddle (description on Stackoverflow). There's also a shorter version (found here): $('#myinput').clone().attr('type','tel') .insertAfter('#myinput') .prev().remove();
  • Chandre Gowda published a solution on StackOverflow that uses ng-switch:

There's also a pull request that tried to add type="{{dynamicTypeFromModel}}", but was redrawn after two weeks of discussion.

There's hope: AngularJS 1.3 and AngularJS 2.0 have dropped support for Internet Explorer 8, so maybe we will see ng-type in future.

As Kabby points out in the comments section, you can use interpolation with the type attribute in AngularJS 1.2.13. So probably this has silently been fixed.


Comments