SAPUI5 Development

When to use expression binding in SAPUI5?

             Expression Binding is a type of binding use when we have to do some simple calculations or formatting in the view itself in SAPUI5. The benefit of using expression binding is no controller logic is needed.Only view is involved.Less code to achieve formatting.
          We should use expression binding if we need to set the value of a boolean property of a control according to some value. For example if we need to set visibility of a control based on some value in the odata service. Or we need to do a calculation like if the value is greater than some value it should be in red color otherwise green, In situation like these we can make use of expression binding.
syntax
"{= ${Price} > 15 ? 'Error' : 'Success' }"

Steps
  1. Open controller in my case View1.controller.js and inside onInit method add below code.This is the custom data for our list.In real cases the data should be coming from backend OData service or rest apis. Here we use a json model and set it to the view.
  2.   onInit: function() {
       var data = {
        "Products": [{
         "Product": "Pineapple",
         "Price": "20",
        }, {
         "Product": "Orange",
         "Price": "10",
        }, {
         "Product": "Grape",
         "Price": "15",
        }]
       };
       var oModel = new sap.ui.model.json.JSONModel();
    
       oModel.setData(data);
       this.getView().setModel(oModel);
      },
    
  3. Open View1.view.xml and paste below code.For the numberState property we have used expression binding. Check the syntax. The syntax starts with = inside the brackets. This symbol is used to initiate a new binding syntax, its called an expression and we can use ternary operator like below.
  4. <List class="sapUiResponsiveMargin" width="auto" items="{/Products}">
        <items>
            <ObjectListItem title="{Product}" number="{Price}" numberUnit="$" numberState="{= ${Price} > 15 ? 'Error' : 'Success' }" />
        </items>
    </List>
    
  5. Run the application and see the magic with just one line of code.
We have made the numbers greater than 15 to red color and rest green color. No hassle of controller logic.
If you enjoyed this post, Please Share!!

1 comments :

  1. If I have to bind numberState according to Price and Quantity then how to use AND,OR operators in above example?

    ReplyDelete

Powered by Blogger.