How to assign [(ngModel)] with an empty/null/undefined object? Angular 4
using [(ngModel)] with nullable types from database
If entity
is a defined class setting entity.publishOn
to a default value of ''
is a simple thing.
If there is a chance that entity
itself is null
then you might be better off exposing the same via a variable in controller with get and set methods something like
private _entity:Entity; // this is the declaration of the variable
...
...
constructor(){
this._entity = new Entity();
}
...
...
get entity():Entity{
return this._entity;
}
set entity(value:Entity):void{
if(value){
this._entity =value;
}else{
this._entity = new Entity() // cases when we want to reset the value
}
}
ng-model - Empty input returns null
If I will have some other inputs and for each input I want other default value I will need to have a lot of directives
You could have a defaultValue
attr for the directive which would be provided while using the directive from HTML. Something like this:
.directive('emptyToDefault', function () {
return {
restrict: 'A',
require: 'ngModel',
scope: {
defaultValue: '='
},
link: function (scope, elem, attrs, ctrl) {
ctrl.$parsers.push(function(viewValue) {
if(viewValue === null) {
return scope.defaultValue || 0;
}
return viewValue;
});
}
};
});
Now you can easily pass different default values from outside and it will be set when string is emptied.
HTML would be like,
<input ng-model="data.value" type="number" placeholder="0" value="0"
empty-to-default default-value="5">
working plunker (open console to notice how it sets default value 5
since string is emptied and passed value is 5
)
Related Topics
Remove Everything After Last Backslash
Prevent Form Submission on Enter Key Press
Validate Phone Number With Yup
Vuejs Error, Invalid Prop: Type Check Failed for Prop. Expected Date, Got Number With Value
Whenever I Click Outside the Element It Should Close
How to Prevent the Keyboard from Popping Up on Mobile Devices
In React Why Does Calling a Function from Another Function in Our Code Not Work and Display
Prevent Html5 Videos from Downloading the Files on Mobile - Videojs
How to Simulate Mouse Click Along With Mouse Move Using JavaScript
How to Write a Postman Test to Compare the Response Json Against Another Json
How to Select Json Response Item With Spaces
Javascript Sum and Group by of Json Data
Jquery Click Events Firing Multiple Times
Check If a String Is HTML or Not
How to Add Query String Parameter to Same Url When on Click a Href Link
Sticky Header Smoothing Scroll Down
Eslint: Disable Warning - 'Defined But Never Used' for Specific Function