Binding in Control with "class" Attribute

UI5 doesn't support binding for class in XML view directly as it's not a valid property of ManagedObject. Nevertheless, there is a workaround by adding custom data:

  1. Add CustomData with the property writeToDomapi to your control. Use your expression binding there:

    <Text xmlns="sap.m" class="myText" text="...">
      <customData>
        <core:CustomData xmlns:core="sap.ui.core"
          key="green"
          value="foo"
          writeToDom="{= expression}"
        />
      </customData>
    </Text>
    

    Depending on the outcome of your expression binding, data-green will be added to the control's HTML element. The browser can then manipulate the color corresponding to the attribute selector.

  2. Your CSS should thus include the selector accordingly:

    .myApp .sapMText.myText[data-green] {
      /* ... */
    }
    

Here is an example: https://embed.plnkr.co/LAv1qfsUjX0Anu7S/

Of course, you can also bind anything you want to the value property of the CustomData in order to react on more granular CSS selectors. To learn more about how to leverage custom data in DOM, check out the documentation topic Writing Data to the HTML DOM as DATA-* Attribute.


Note

  • SAP recommends to avoid specifying colors with custom CSS classes.

    Fiori apps should not override styles. [...] Do not specify colors in custom CSS but use the standard theme-dependent classes instead.

  • There are alternatives when it comes to styling sap.m.Text:
    • Text with semantic colors: sap.m.ObjectStatus, ..ObjectNumber
    • Text with custom formats: sap.m.FormattedText.

Generally, the importance of adding custom CSS styles should be always questioned and double-checked with the stakeholders, not only for UI consistency across Fiori apps but also to reduce the maintenance costs and TCO that would otherwise rise significantly with custom CSS.

Tags:

Css

Sapui5