Safe navigation operator with bracket property accesor

一世执手 提交于 2019-12-25 10:06:21

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!