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:
- defining a
defaultobject and setting for every input the default value when itsnull - addressing the DOM element in the template again, instead of setting null
<myElement #myelem [type]="condition ? 'something' : myelem.type"></myElement>
- defining set / get for every input to prevent null setting
_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!