I have an input field mapped to an entity in my controller with a ngModel
2-way binding.
<input type="text" [(ngModel)]="entity.one_attribute" />
When I initialize my controller, I have this entity :
{ one_attribute: null }
If a user starts to fill in the field but does not submit the form immediately and empties the field, my entity is updated to become:
{ one_attribute: "" }
Is it possible to define that empty string should be changed to null automatically?
After viewing a bunch of answers about
ValueAccessor
andHostListener
solutions, I made a working solution (tested with RC1):Then use it that way on your input fields:
I have done it globally. But its not 100%. I could not find the method where angular 4 call JSON.stringify on the body. I'm hoping someone could help out here. Until the new HttpClient in 4.3 is out I continue to use a wrapper class for the Http service. I do this because no interceptors has been present in Angular2 and forward. My wrapper looks something like this.
So far so good. But I have not found any good transformRequest as in AngularJS, so until i find it I have implemented transformEmptyStringAsNull as this:
I know it's ugly in the way that I will do an extra stringify back to parse again. But I don't need to do anything in the rest of the application.
I just formed this solution after much research. It's kind of hacky since the Angular team doesn't recommend extending
DefaultValueAccessor
, but it automagically works for every input without having to mark each one individually.This is working great for me on Angular 4.4.5.