3

I want to dynamically change font color of a Vaadin Flow TextField component.

Tried this, but does not work:

textField.getElement().setProperty("color", "red");

I suspect this is because the <input> element is hidden in the shadow dom. I have no clue how to handle this.

BTW I am aware of the Dynamic Styling tutorial.

rmuller
  • 12,062
  • 4
  • 64
  • 92
  • Have you checked this question and answer?https://stackoverflow.com/questions/53126339/dynamically-changing-font-font-size-font-color-and-so-on-in-vaadin-flow-web-a/53129202 – Tatu Lund Jan 26 '19 at 12:19
  • 1
    I have not yet tested it myself, but I think solution to your problem is to define themable mixin with "input-element" part and use custom property for font color there, which you define in your global styles, and then you can dynamically change value of the custom property. – Tatu Lund Jan 26 '19 at 12:20
  • 1
    Thanks. Yes, i have seen that question. I have not seen example code of how to create a themable mixin and custom properties in the Java (Flow) code. A cannot get the complete picture yet. Besides that, is this not an overly complex approach for a rather common and simple use-case? – rmuller Jan 26 '19 at 13:21
  • 2
    There is another question and answer about the same topic, which has an example about text field styling with themable mixin, see: https://stackoverflow.com/questions/53141129/vaadin-flow-10-11-style-component-via-css/53151242#53151242 – Tatu Lund Jan 26 '19 at 15:13
  • Thanks Tatu, it is now clear for me – rmuller Jan 27 '19 at 13:55

2 Answers2

0

If you don't care that the text color of the label above the input field also turns red, you also could use this in combination (tested with Vaadin 14.2.1, in current Firefox and Chromium):

textField.getElement().getStyle().set("color", "red");
textField.getElement().getStyle().set("-webkit-text-fill-color", "red");
S. Doe
  • 685
  • 1
  • 6
  • 25
0

With the Custom Theme feature, you can add your custom theme @Theme(value = "my-theme"), create a CSS stylesheet file ${project.basedir}/frontend/themes/my-theme/components/vaadin-text-field.css and place the following there:

:host(.my-class-red) [part="input-field"]{
    color:red
}

:host(.my-class-blue) [part="input-field"]{
    color:blue
}

On the Java side:

TextField name = new TextField("Your name");
name.setLabel("My label");
        
Button red = new Button("Red", click -> {
   name.removeClassName("my-class-blue");
   name.addClassName("my-class-red");
});

Button blue = new Button("Blue", click -> {
   name.removeClassName("my-class-red");
   name.addClassName("my-class-blue");
});

Button reset = new Button("Reset", click -> {
   name.removeClassNames("my-class-red", "my-class-blue");
});

add(red, blue, reset);