Home > database >  Apps Script: Change or modify bold, foreground color and style in general (TypeError: format.getText
Apps Script: Change or modify bold, foreground color and style in general (TypeError: format.getText

Time:09-08

I have the following definition:

format = SpreadsheetApp.newTextStyle()
        .setForegroundColor(spec.textColor)
        .setBold(spec.bold)
        .build();

I want to modify it, but I have not been able so far. Some examples of unlucky attempts:

The following, returns the error: TypeError: format.setForegroundColor is not a function: format.setForegroundColor("green");

The following, returns the error: TypeError: format.getTextStyle is not a function: format.getTextStyle().setForegroundColor("yellow");

The following does nothing: format.setForegroundColor = "green";

The following DO work, but it does not seem a proper/elegant solution (as we are basically creating the variable again instead modifying a value of it):

format = SpreadsheetApp.newTextStyle()
        .setForegroundColor("green")
        .setBold(spec.bold)
        .build();

How to properly modify the foreground color or bold attribute?

CodePudding user response:

You cannot modify a TextStyle once its been built. The built-in SpreadsheetApp service creates TextStyle instances by employing the Builder design pattern which generally produces an immutable object as a final result. So you can't invoke the methods you used in the build process on the final object.

However, you can generate a new TextStyleBuilder from an existing TextStyle by using the TextStyle::copy() function.

const textStyleBuilderA = SpreadsheetApp.newTextStyle();
const textStyleA = textStyleBuilderA
        .setForegroundColor(spec.textColor)
        .setBold(spec.bold)
        .build();

const textStyleBuilderB = textStyleA.copy();
// Note that you only need to change the foreground color
// since the bold setting is inherited
const textStyleB = textStyleBuilderB
        .setForegroundColor('green')
        .build();
  • Related