Created
April 23, 2024 09:52
-
-
Save TatuLund/4ab9ccf292093659ce6fa28547ea2797 to your computer and use it in GitHub Desktop.
A Vaadin code example how to create web component with shadow root in Java.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package org.tatu.components; | |
import com.vaadin.flow.component.Component; | |
import com.vaadin.flow.component.Html; | |
import com.vaadin.flow.dom.Element; | |
import com.vaadin.flow.dom.ShadowRoot; | |
// Example of slotting of child component: | |
// component.getElement().setAttribute("slot", "content"); | |
// String html = "<div><slot name='content'></slot></div>"; | |
// CustomComponent cc = new CustomComponent("custom-comp", html); | |
// cc.getElement().appendChild(grid.getElement()); | |
public class CustomComponent extends Component { | |
/** | |
* Wrap Html component as web component with given tag name. | |
* | |
* @param tag | |
* Tag name, needs to have at least one -, e.g. "tag-name" | |
* @param html | |
* Html component. | |
*/ | |
public CustomComponent(String tag, Html html) { | |
super(null); | |
setup(tag, html); | |
} | |
/** | |
* Generate web component using tag name and given HTML fragment with a | |
* single root element. | |
* | |
* @param tag | |
* Tag name, needs to have at least one -, e.g. "tag-name" | |
* @param htmlString | |
* HTML fragment with a single root element. | |
*/ | |
public CustomComponent(String tag, String htmlString) { | |
super(null); | |
Html html = new Html(htmlString); | |
setup(tag, html); | |
} | |
private void setup(String tag, Html html) { | |
Element el = new Element(tag); | |
setElement(this, el); | |
el.attachShadow(); | |
ShadowRoot shadow = el.getShadowRoot().get(); | |
shadow.appendChild(html.getElement()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment