2

I work with SAPUI5, and I want to add a style to an object as soon as I instantiate it. For example, I want to add styleclass 'foo' to my label inside my panel.

What I want to do, but doesn't work:

var oPanel = new sap.m.Panel({
 content: new sap.m.Label({
 text: "Hello",
 styleClass: "foo"
 })
});

What I don't want to do, but does work:

var oLabel = new sap.m.Label({
text: "Hello"
});
oLabel.addStyleClass("foo");

var oPanel = new sap.m.Panel({
content: oLabel
});
Daniël Camps
  • 1,737
  • 1
  • 22
  • 33
  • 3
    You´re right, it is a missing feature. Only XML Views support it. However, what´s the reason you don´t want to call `addStyleClass()`? Since the rendering won´t be triggered at that moment it makes no difference. See http://stackoverflow.com/q/29508061/1969374. – Tim Gerlach Apr 13 '15 at 15:10
  • 1
    Another plus in favor of using XMLViews ;-) – Qualiture Apr 14 '15 at 16:32
  • Thank you for the replies, and haha Qualiture :) I only want it to make my code more concise and readable for colleagues. Thank you for the answer and reference Tim, I looked but didn't find it. – Daniël Camps Apr 15 '15 at 19:09
  • Hi Daniel, I don't think it is explicitly mentioned somewhere (which is an omission IMO) but at https://sapui5.hana.ondemand.com/sdk/docs/guide/b564935324f449209354c7e2f9903f22.html there is a reference to the `class` property in an XML control – Qualiture Apr 17 '15 at 06:51

3 Answers3

3

There's another option based on method chaining which does not require a dedicated variable for the inner elements (which I guess is the reason why you do not like the 2nd variant in your question):

var oPanel = new sap.m.Panel({
   content: new sap.m.Label({ text: "Hello" }).addStyleClass("foo")
});
Alex
  • 168
  • 10
1

you can even write your own custom classes where the style class is an aggregation. I am not sure as yet how this can be done but I was able to write custom labels with 'color' aggregation.

0

You could create a function to return your control instances, and inside of it make use of the addStyleClass method, and others you would like

function getControlInstance(FnClass, sId, mSettings) {
    mSettings = mSettings || {};
    if (typeof sId !== "string") {
        mSettings = sId;
        sId = null;
    }
    var oControl = new FnClass(sId, mSettings);
    if (mSettings.styleClass) {
        mSettings.styleClass = mSettings.styleClass instanceof Array ? mSettings.styleClass : [mSettings.styleClass];
        mSettings.styleClass.forEach(function (sClass) {
            oControl.addStyleClass(sClass);
        });
    }
    return oControl;
}

Use like this

var a = getControlInstance(sap.m.HBox, {
    styleClass: "test",
    id: "asdoiasd",
    items: [
        new getControlInstance(sap.m.Text, {
            styleClass: "test",
            text: "Testing"
        })
    ]
})
Guilherme Ferreira
  • 2,209
  • 21
  • 23