angular: NgModel convert model to string, when input[type] doesn't number.

I’m submitting a…


[ ] Regression (a behavior that used to work and stopped working in a new release)
[x] Bug report  
[ ] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead see https://github.com/angular/angular/blob/master/CONTRIBUTING.md#question

Current behavior

When input[type=“text”] ngModel convert model to string.

Expected behavior

If model is number or something else, it should be save its type

Minimal reproduction of the problem with instructions

Logic

class Foo {
	public bar = {
		foo: 42
	}

	onFocusOut(): void {
		console.log (typeof bar.foo) //string
	}
}

Template

<input type="text" [(ngModel)]="bar.foo" (blur)="onFocusOut()">

What is the motivation / use case for changing the behavior?

Backend returns value and Frontend need to do something with that, then update that one at Backend side. On condition if type of that value didn’t change backend will update that one.

Ok i can convert that value at the logic side, but if i don’t know about type changed. Or don’t want to excess actions with type converting.

Environment


Angular version: 4.4.3


Browser:
- [ ] Chrome (desktop) version XX
- [ ] Chrome (Android) version XX
- [ ] Chrome (iOS) version XX
- [ ] Firefox version XX
- [ ] Safari (desktop) version XX
- [ ] Safari (iOS) version XX
- [ ] IE version XX
- [ ] Edge version XX
 
For Tooling issues:
- Node version: XX  
- Platform:  

Others:

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Reactions: 1
  • Comments: 15 (8 by maintainers)

Most upvoted comments

@andremarcondesteixeira If you want such behavior, you can implement it yourself – it’s a great use-case for a custom directive. You can even publish it to NPM and reuse it in all projects. But it’s not something that Angular as a framework should support out of the box.

As others have mentioned, it’s expected behavior that changes to a text field would produce a string value. If you’d like to convert the string to a different type, a custom control value accessor or a number field are both viable options.

Likely it should just throw at first place when value past is not string, so there won’t be any consistency problem.

I disagree. If you have a masked numeric input, the type should be a string and the model should be a number. If you just used [type=“number”] some browsers would not allow some mask characters to be inserted.

I think it works as intended. If your data-bound model property is a number just use type="number" to avoid string coercion.