I wonder what is the "Angular/Typescript way" to set up default values for optional properties in Angular component? I am having troubles when values passed to optional properties are null
or undefined
.
Currently I am having something like this:
export class FooComponent implements OnInit {
@Input() foo = 'foo';
@Input() bar = 0;
@Input() baz?: string;
}
If you declare default value, you dont have to specify type since it is type of assigned value and property is optional by default. This is the case of bar
and foo
properties.
Alternatively you can use ?
to mark that this property is optional but you cant declare its default value. This is the case of baz
property.
Now let us see what happens when you pass different values to those properties.
<app-foo-component
[foo]
[bar]="null"
[baz]="undefined"
>
</app-foo-component>
if I console log these properties, this is what I got:
foo
will be correctly 'foo'
bar
will be null
baz
will be undefined
Is there a elegant way to also set default values when passed values are null/undefined or do I need some checking in OnInit like this?
OnInit() {
this.bar = this.bar || 0;
}
It feels like there is some way to do this. To me, optional property means that value could be missing, null or unset but when I want to set default value, it only works when property is missing or empty. It still set value as null or undefined in these cases and that seems to be confusing.