问题
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?
回答1:
Can you initialize the translations obj? It would avoid any error.
translations = {}
回答2:
What I did was the following:
[matTooltip]="translations ? translations['Tooltip.O2'] : null"
回答3:
You can use conditional operator for null
check
[matTooltip]="translations ? translations['Tooltip.O2'] : null"
来源:https://stackoverflow.com/questions/48350245/safe-navigation-operator-with-bracket-property-accesor