Wednesday 2 February 2011

How to Display HTML text in the Spark TextArea

 It isn’t immediately obvious how to display HTML text in a Spark TextArea. Back in the MX days we had textArea.htmlText which is pretty easy to use. But no such beast on the Spark version.
With a Spark text component you have to run your HTML text through a multi-dimensional phase-inducer which is handily provided through spark.utils.TextFlowUtil.importFromString( myHTMLtext );
But you don’t send the output of the importFromString method to the textArea.text. No, no, no. That would be toooo easy. With Spark there’s a new thingy called textFlow. That’s what gets the output of the importFromString() method.

Here’s a very simple example
myTextArea.textFlow = spark.utils.TextFlowUtil.importFromString(
  'some <span fontWeight="bold">bold</span> text.' );

There are a few issues that I’ve found with the new Spark Text components. First, I cannot get embeded <span> tags to render. For instance I can’t change the fontWeight to bold and also change the fontSize to, say, 16 on the same text. I’m not sure what’s up with that.
Also, I cannot get unordered-lists to display at all. Perhaps these are just issues that will be resolved when Flex4 is ready for primetime. If you know anything about this I’d love to read about it in the comments.
One interesting bonus I found is that creating a link automatically turns the text blue and underlines it. I’m not sure how you would override that but it’s nice that it doesn’t show up as just regular un-formatted text.
What’s funny is that starting out this was just going to be a simple example with two text fields where you could type in your HTML and then see it rendered below. Then I thought I’d add a button to make the selected text bold. And then italic. And on and on. Sometimes I just don’t know when to quit.
More examples at  Setting text in a Spark RichText control in Flex 4 at blog.FlexExamples.com.

Note also that you may use the old mx:TextArea where support your favorite htmltext propetry
open the source view of your mxml, and drop the follow lines
    <mx:TextArea x="0" y="2" width="400" height="200">
    </mx:TextArea>

1 comment:

  1. list item tags are not supported at all. This appears intentional as there is a specific note regarding lists in the documentation. Here is a link to the rather obscurely burried supported tags info: http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flashx/textLayout/conversion/TextConverter.html#TEXT_FIELD_HTML_FORMAT

    ReplyDelete