We are developing components and when using them, we would like to use the same mechanism like for DOM nodes to conditionally define attributes. So for preventing attributes to show up at all, we set the value to null and its not existing in the final HTML output. Great!
<button [attr.disabled]="condition ? true : null"></button>
Now, when using our own components, this does not work. When we set null, we actually get null in the components @Input as the value. Any by default set value will be overwritten.
...
@Component({
selector: 'myElement',
templateUrl: './my-element.component.html'
})
export class MyElementComponent {
@Input() type: string = 'default';
...
<myElment [type]="condition ? 'something' : null"></myElement>
So, whenever we read the type in the component, we get null instead of the 'default' value which was set.
I tried to find a way to get the original default value, but did not find it. It is existing in the ngBaseDef when accessed in constructor time, but this is not working in production. I expected ngOnChanges to give me the real (default) value in the first change that is done and therefore be able to prevent that null is set, but the previousValue is undefined.
We came up with some ways to solve this:
default object and setting for every input the default value when its null<myElement #myelem [type]="condition ? 'something' : myelem.type"></myElement>
_type: string = 'default';
@Input()
set type(v: string) {if (v !== null) this._type = v;}
get type() { return this._type; }
but are curious, if there are maybe others who have similar issues and how it got fixed. Also I would appreciate any other idea which is maybe more elegant.
Thanks!
ACCEPTED]
There is no standard angular way, because many times you would want null or undefined as value. Your ideas are not bad solutions. I got a couple more
ngOnChanges hook for this:@Input()
type: string = 'defaultType';
ngOnChanges(changes: SimpleChanges): void {
// == null to also match undefined
if (this.type == null) {
this.type = 'defaultType';
}
}
Observables:private readonly _type$ = new BehaviorSubject('defaultType');
readonly type$ = this._type$.pipe(
map((type) => type == null ? 'defaultType' : type)
);
@Input()
set type(type: string) {
this._type$.next(type);
}
function Default(value: any) {
return function(target: any, key: string | symbol) {
const valueAccessor = '__' + key.toString() + '__';
Object.defineProperty(target, key, {
get: function () {
return this[valueAccessor] != null ? this[valueAccessor] : value
},
set: function (next) {
if (!Object.prototype.hasOwnProperty.call(this, valueAccessor)) {
Object.defineProperty(this, valueAccessor, {
writable: true,
enumerable: false
});
}
this[valueAccessor] = next;
},
enumerable: true
});
};
}
which you can use like this:
@Input()
@Default('defaultType')
type!: string;
[1] http://www.typescriptlang.org/play/?experimentalDecorators=true&emitDecoratorMetadata=true&ssl=24&ssc=2&pln=1&pc=1#code/GYVwdgxgLglg9mABAEQKbAIYgDZQBQBuG2IqAXIhmAJ4CUiA3gFCKIBOqUIbSoksCPFAxsA5pwpVqAGkQBrVNQoBnKGxhhRiAD6Jl1ALYAjONnrNWrCAlWIiJVAEEIEVMuVw2iALyIA5AD6AX6IANTyigB0UHAAymoaonj04YHBANxMLJYA8kYAVqjQkQAm6BqoAApscAAOqGxQ1EIi4lCyCjKM2ZaIbRR80PBIyd29vRxcPIhQABYwygDa9qTOru6eALqIAIS+YDjYiAD8M-NLK04ubh5s2xSXPZYAvtJPrMoSiIMCI2CoAA8oOZ3pYYMBEHgdnlCsVajUYk16pFZhhlDkAO5gap1BpNSIQYjYITnWSXNY3Ty0EHjcYwopQUrlf44+qNZpzBZk4ira4bNiyCy08YY9TCIzYcgzNikN7C8aoA4GBoYCVSzDYT5y+WWaxgYAwUTcVWSihqUig3rPWiZeXPLLyzkXHlXda3bb7QFQW3jV6gxUgZVsE1S82obW9PUGo3BtVmmXhp7Wn3PTL2pgQbBo5SIAAqblgmjGiAAAmhMDh8ABGWjZKAF44UJVGBqZbJ61Qy6CeIQNpuBltsGmWJ3RAs+GYFlNMdMdqCT1RVif-DF5guJPAAJhtGZs8-rqk3y9Qq-zqg3O7nC6gAGZj6f15o8ABWHdMA+3se2Xybqs3tsdqYqCRNgcBJB+VZfu016blBsgfjeUFvsAniQleGCIBo141sW4KQhgkSqCIUDKAA6jAcx4GkfjUsWVg2EBIFgXgGA7qw9r2kAAfor .. in loop it would show the value accessor property as well. By declaring it directly in the this.set and setting enumerable to false it won't show up anymore. - Poul Kruijt
valueAccessor value :) - Poul Kruijt
val variable in the decorator will hold only the last changed value. We need the class to hold the value for this to work. Thank you for the feedback @PoulKruijt, I updated my stackblitz example with a new test to check for this issue - ndraiman
Just one more option (perhaps simpler if you don't want to implement your own custom @annotation) based off Poul Krujit solution:
const DEFAULT_VALUE = 'default';
export class MyElementComponent {
typeWrapped = DEFAULT_VALUE;
@Input()
set type(selected: string) {
// this makes sure only truthy values get assigned
// so [type]="null" or [type]="undefined" still go to the default.
if (selected) {
this.typeWrapped = selected;
} else {
this.typeWrapped = DEFAULT_VALUE;
}
}
get type() {
return this.typeWrapped;
}
}
null or undefined it won't change the typeWrapped property, and your default value is gone. - Poul Kruijt
If you need to do this for multiple inputs, you can also use a custom pipe instead of manually defining the getter/setter and default for each input. The pipe can contain the logic and defaultArg to return the defaultArg if the input is null.
i.e.
// pipe
@Pipe({name: 'ifNotNullElse'})
export class IfNotNullElsePipe implements PipeTransform {
transform(value: string, defaultVal?: string): string {
return value !== null ? value : defaultVal;
}
}
<!-- myElem template -->
<p>Type Input: {{ type | ifNotNullElse: 'default' }}</p>
<p>Another Input: {{ anotherType | ifNotNullElse: 'anotherDefault' }}</p>