Search code examples
sapui5

How to remove added items using ID from controller


I have tried adding buttons to HBox and FlexBox dynamically

In the XML view i have did as below:

<HBox id="upperchart">
    <m:Input value=" Key Code " editable='false' width='360px'/> 
</m:HBox>
<FlexBox
    alignItems="Start" id="lowerchart">
<FlexBox>

In the controller I tried accessing these with the ID's as

Controller:

var lowerHBox = this.getView().byId("lowerchart");
var upperHBox = this.getView().byId('upperchart');
var oHBox = new sap.m.HBox();
oHBox.addItem(new sap.m.Input({
    value: "Test Data",
    editable: false,
    width: graphWidth*10 + 'px'
}));
upperHBox.addItem(oHBox);

var oMyFlexbox = new sap.m.FlexBox();
// I am adding Buttons to HBox dynamically
for (var i = 0; i < 5.length; i++){
    oMyFlexbox.addItem(new sap.m.Button({
        text: "Button",
        width: allWidths[i]*10 + 'px'
    }));
}
lowerHBox.addItem(oMyFlexbox);

Here the thing is When i just navigate through the page it gets created multiple times.

so i have tried to remove on first and add as again under this as:

lowerHBox.removeItem();
upperHBox.removeItem();

But this doesn't work to my luck ,

May I know how can I avoid it creating again and again or check if items already exists remove and create a new like this..

Any help or guiding links are appreciated thanks in advance.


Solution

  • You can remove the items of HBox here as:

      lowerHBox.removeAllItems();
      upperHBox.removeAllItems();
    

    This could remove Items which I understood is one of your Q's

    link to docs:

    https://sapui5.hana.ondemand.com/#/api/sap.m.HBox%23methods/Summary

    I Would wait for other expert's say for more efficient way :)