How to add html format on a vaadin label?

巧了我就是萌 提交于 2021-01-29 19:12:42

问题


I want to add an html formatted string on a vaadin label. The string comes from a database and goes straight to the label, it must be formatted with bold text, line breaks and some other fancy text things. I found a couple of solutions but those were for old version of vaadin, is there any way of doing this on vaadin flow?


回答1:


You could add an HTML content to a label using:

        Label label = new Label();
        label.getElement().setProperty("innerHTML","A new line should be created after this <br /> <b>This text is bold</b> <br /> <i> This text is italic</i>");
        add(label);

BUT, if you want to display only text, then the label is not a correct element to use. As stated in its API :

Note that Label components are not meant for loose text in the page - they should be coupled with another component by using the setFor(Component) or by adding them to it with the HasComponents.add(Component...) method.

I would use the HTML element instead :

        String yourContent ="A new line should be created after this <br /> <b>This text is bold</b> <br /> <i> This text is italic</i>";
        Html html = new Html("<text>" + yourContent + "</text>");
        add(html);

The output :

Or you could encapsulate the functionality and create a general component for displaying an HTML snippets based using an example here : https://vaadin.com/forum/thread/17072019



来源:https://stackoverflow.com/questions/61860660/how-to-add-html-format-on-a-vaadin-label

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!