Change icon color if condition

2019-04-13 06:52发布

问题:

I am using a list that prints data from a model and one should have an icon. The thing is that the icon changes depending on the value and I should also change its color.

I have in my view :

<ObjectListItem title="State" type="Active" number="{/Data/8/state}"
icon="{= ${/Data/8/state}.toUpperCase() === 'OK' ? 'sap-icon://accept' : 
'sap-icon://decline' }"></ObjectListItem>

Options like addStyleClass doesn't seem to work. I have changed the color by adding css to the id that SAP adds to the Icon, but since it has to change according to the value I don't know how to achieve it. Another option was to add color directly to these two icons but I wasn't able to add the classes.

回答1:

You can use CustomData and then create a css selector to match it:

<ObjectListItem title="State" type="Active" number="{/Data/8/state}"
icon="{= ${/Data/8/state}.toUpperCase() === 'OK' ? 'sap-icon://accept' : 
'sap-icon://decline' }">
<customData>
  <core:CustomData writeToDom="true" key="class" value="{= ${/Data/8/state}.toUpperCase()}" />
</customData>
</ObjectListItem>

This will render your control with an additional data-class attribute (actually, data-{key}, where key is the key that you defined on your core:CustomDatatag).

You can then match that with the CSS selector

[data-class='OK'] {
  color: blue !important; 
}
[data-class='NOT-OK']{
  color: red !important;
}


标签: sapui5