Safe navigation operator with bracket property accesor

2.2k Views Asked by At

I've run into a case where I can't use the dot notation to access a property, because the property's name contains a dot.

I have an object called translations whose properties contain string translations, for example the Tooltip.O2 property contains the translation for the tooltip of an image:

<img [matTooltip]="translations?.Tooltip.O2" [src]="bed.additionalO2 ? medO2 : noO2">

When I do this, it thinks I'm trying to access a Tooltip object inside translations with an O2 property. I'm aware that I can use the bracket notation to access it:

[matTooltip]="translations['Tooltip.O2']"

However, it does not seem like the safe navigation operator ? can be used with the bracket notation. I've tried to write translations?['Tooltip.O2'], but it caused errors.

I would like to know if there is there a way to access the property using the dot notation, or if there is a way to use the safe navigtaion operator with the bracket notation?

4

There are 4 best solutions below

0
Jesper On

What I did was the following:

[matTooltip]="translations ? translations['Tooltip.O2'] : null"
0
Leandro Lima On

Can you initialize the translations obj? It would avoid any error.

translations = {}
0
s sharif On

You can use conditional operator for null check

[matTooltip]="translations ? translations['Tooltip.O2'] : null"
0
Pavol Hlavatý On

There is a way to use safe navigation operator with bracket notation. Actually safe navigation operator is officialy called optional chaining operator. Syntax from the docs:

obj.val?.prop
obj.val?.[expr]
obj.arr?.[index]
obj.func?.(args)

So in your case you need to use translations?.['Tooltip.O2'].