How to Assign [(Ngmodel)] With an Empty/Null/Undefined Object - Angular 4

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



Leave a reply



Submit