Safe navigation operator with bracket property acc

2019-08-24 15:19发布

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?

3条回答
淡お忘
2楼-- · 2019-08-24 15:33

You can use conditional operator for null check

[matTooltip]="translations ? translations['Tooltip.O2'] : null"
查看更多
戒情不戒烟
3楼-- · 2019-08-24 15:42

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

translations = {}
查看更多
仙女界的扛把子
4楼-- · 2019-08-24 15:48

What I did was the following:

[matTooltip]="translations ? translations['Tooltip.O2'] : null"
查看更多
登录 后发表回答