3

My question is related to this post in the "old" Vaadin Forum. I want to set the initial row number of the Vaadin TextArea to 1, so it looks like a TextField.

The mentioned post has the solution:

This requires a bit of JavaScript to fix. You need to set rows=1 to the internal element

<textarea part="value"></textarea>

Unfortunately I do not know how to apply this solution, as I am still a JS and CSS beginner. We already have some JS-code adjusting TextAreas (and other components), maybe at this part I need to add some code?

const $_documentContainer = document.createElement('template');

$_documentContainer.innerHTML = `<dom-module id="our-project-text-area" theme-for="vaadin-text-area"> 
  <template> 
   <style> {            
      :host [part="input-field"] {
        font-weight: lighter;
      }
      
      :host [part="input-field"]::after {
        background-color: var(--mainColor);
      }
      
      :host([focused]:not([invalid])) [part="label"] {
        color: var(--mainColor);
      }
      }
    </style> 
  </template> 
 </dom-module>`;

document.head.appendChild($_documentContainer.content);

Can you please help me how to add attributes to a specific element inside the TextAreas Shadow DOM?

Mathias
  • 282
  • 1
  • 16

1 Answers1

4
var textArea = new TextArea();
textArea.getElement().executeJs("this.shadowRoot.querySelector('textarea').rows = $0;", rows);

this refers to the element you have selected with getElement(), so it will be the <vaadin-text-area> HTML element.

The querySelector method basically find an element based on a CSS selector, in this case we want to select the <textarea> inside the shadow root. You could select it with more specific CSS or with the [part='value'] but since the rows property is inherent to the textarea tag I think it is okay to sleect that.

Hawk
  • 2,042
  • 8
  • 16
  • Thanks a lot, it works perfectly! Until now I did not stumble upon getElement().executeJS(...), this makes the code nicely readable and compact. Also thanks a lot for the explanation. This input should get me started on playing with JS. – Mathias Jun 15 '21 at 13:47
  • 2
    I personally avoid using JS except when necessary. It could get out of hand pretty quickly. And if you needed anything more complicated than a simple-ish one-liner I recommend using a separate .js file and import that (https://vaadin.com/docs/v14/flow/importing-dependencies/tutorial-importing). – Hawk Jun 15 '21 at 18:51