Sometimes the predefined types of OpenUI5 are not flexible enough and you want to do a simple calculation or formatting in the view - that is where expressions are really helpful. We use them to format our price according to the current number in the data model.
The price is now formatted according to its number
You can access the live preview by clicking on this link: 🔗 Live Preview of Step 21.
To download the solution for this step as a zip file, just choose the link here: 📥 Download Solution for Step 21.
We add the numberState
attribute to the ObjectListItem
control in our invoices list view. We use the '=' symbol to initiate an expression binding and specify that the number in numberState
appears in red, in case the price is greater than 50, otherwise in green.
<mvc:View
controllerName="ui5.walkthrough.controller.InvoiceList"
xmlns="sap.m"
xmlns:mvc="sap.ui.core.mvc">
<List
headerText="{i18n>invoiceListTitle}"
class="sapUiResponsiveMargin"
width="auto"
items="{invoice>/Invoices}" >
<items>
<ObjectListItem
title="{invoice>Quantity} x {invoice>ProductName}"
number="{
parts: [
'invoice>ExtendedPrice',
'view>/currency'
],
type: 'sap.ui.model.type.Currency',
formatOptions: {
showMeasure: false
}
}"
numberUnit="{view>/currency}"
numberState="{= ${invoice>ExtendedPrice} > 50 ? 'Error' : 'Success' }"/>
</items>
</List>
</mvc:View>
Expression binding can do simple calculation logic like the ternary operator shown here.
The condition of the operator is a value from our data model. A model binding inside an expression binding has to be escaped with the $
sign as you can see in the code. We set the state to "Error" (the number will appear in red) if the price is higher than 50 and to "Success" (the number will appear in green) otherwise.
Expressions are limited to a particular set of operations that help formatting the data such as Math expression, comparisons, and such. You can look up the possible operations in the documentation.
- Only use expression binding for trivial calculations.
Next: Step 22: Custom Formatters
Previous: Step 20: Data Types
Related Information