TextArea
The TextArea component provides multi-line text input and automatically wraps text to ensure that no line extends beyond the component's width.
If the component does not have its height set, it adapts its height to the content. If the component does not have its width set, it stretches to fill the maximum available width.
NOTE
This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
Child Components
Not supported
APIs
TextArea(value?: TextAreaOptions)
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.ArkUI.ArkUI.Full
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| value | TextAreaOptions | No | Parameters of the TextArea component. |
TextAreaOptions
Describes the initialization options of the TextArea component.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.ArkUI.ArkUI.Full
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| placeholder | ResourceStr | No | Yes | Text displayed when there is no input. When only the placeholder attribute is set, the text selection handle is still available; the caret stays at the beginning of the placeholder text when the handle is released. |
| text | ResourceStr | No | Yes | Current text input. You are advised to bind the state variable to the text in real time through the onChange event, so as to prevent display errors when the component is updated. Since API version 10, this parameter supports two-way binding through $$. Since API version 18, this parameter supports two-way binding through !!. |
| controller8+ | TextAreaController | No | Yes | Text area controller. |
Attributes
In addition to the universal attributes, the following attributes are supported.
NOTE
The default value of the universal attribute padding is as follows:
{
top: '8vp',
right: '16vp',
bottom: '8vp',
left: '16vp'
}Since API version 11, .width('auto') can be set for the TextArea component. Under this setting, the component auto-adapts its width to the text width, while respecting the constraintSize configuration and the maximum and minimum width restrictions received by the parent container. For details, see Sizing.
placeholderColor
placeholderColor(value: ResourceColor)
Sets the placeholder text color.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.ArkUI.ArkUI.Full
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| value | ResourceColor | Yes | Placeholder text color. The default value follows the theme. |
placeholderFont
placeholderFont(value: Font)
Placeholder text style, including the font size, font weight, font family, and font style.
NOTE
You can use loadFontSync to register custom fonts.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.ArkUI.ArkUI.Full
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| value | Font | Yes | Placeholder text style. |
textAlign
textAlign(value: TextAlign)
Sets the horizontal alignment of the text.
Available options are TextAlign.Start, TextAlign.Center, and TextAlign.End. TextAlign.JUSTIFY is available since API version 11.
The vertical position of the text paragraph can be controlled by the align attribute, but the horizontal position cannot be controlled by align in this component.
-
Alignment.TopStart, Alignment.Top, Alignment.TopEnd: Content aligns to the top.
-
Alignment.Start, Alignment.Center, Alignment.End: Content is centered vertically.
-
Alignment.BottomStart, Alignment.Bottom, Alignment.BottomEnd: Content aligns to the bottom.
When textAlign is set to TextAlign.JUSTIFY, the text in the last line is horizontally aligned with the start edge.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.ArkUI.ArkUI.Full
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| value | TextAlign | Yes | Horizontal alignment of the text. Default value: TextAlign.Start |
NOTE
textAlign only adjusts the overall text layout and does not affect character display order. For character display order adjustment, see Bidirectional Text Layout and Alignment.
textDirection23+
textDirection(direction: TextDirection | undefined)
Specifies the text layout direction. If this attribute is not set, the default text layout direction follows the component layout direction.
Atomic service API: This API can be used in atomic services since API version 23.
System capability: SystemCapability.ArkUI.ArkUI.Full
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| direction | TextDirection | undefined | Yes | Text layout direction. If this parameter is set to undefined, the text layout direction follows the component layout direction as defined by TextDirection.DEFAULT. |
caretColor
caretColor(value: ResourceColor)
Sets the color of the caret in the text box.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.ArkUI.ArkUI.Full
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| value | ResourceColor | Yes | Color of the caret in the text box. Default value: '#007DFF' |
NOTE Since API version 12, this API can be used to set the text handle color, which is the same as the caret color.
fontColor
fontColor(value: ResourceColor)
Sets the font color.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.ArkUI.ArkUI.Full
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| value | ResourceColor | Yes | Font color. |
fontSize
fontSize(value: Length)
Sets the text size.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.ArkUI.ArkUI.Full
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| value | Length | Yes | Font size. If fontSize is of the number type, the unit fp is used. The default font size is 16 fp on non-wearable devices and 18 fp on wearable devices. This parameter cannot be set in percentage. |
fontStyle
fontStyle(value: FontStyle)
Sets the font style.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.ArkUI.ArkUI.Full
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| value | FontStyle | Yes | Font style. Default value: FontStyle.Normal |
fontWeight
fontWeight(value: number | FontWeight | ResourceStr)
Sets the font weight. If the value is too large, the text may be clipped depending on the font.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.ArkUI.ArkUI.Full
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| value | number | FontWeight | ResourceStr | Yes | Font weight. For the number type, the value range is [100, 900], at an interval of 100. The default value is 400. A larger value indicates a heavier font weight. For the string type, only strings that represent a number, for example, "400", and the following enumerated values of FontWeight are supported: "bold", "bolder", "lighter", "regular", and "medium". Default value: FontWeight.Normal The Resource type is supported since API version 20. |
fontFamily
fontFamily(value: ResourceStr)
Sets the font family.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.ArkUI.ArkUI.Full
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| value | ResourceStr | Yes | Font family. Default font: 'HarmonyOS Sans' To specify multiple fonts, separate them with commas (,), and fonts are applied in priority order. Example: 'Arial, HarmonyOS Sans'. |
NOTE
You can use loadFontSync to register custom fonts.
inputFilter8+
inputFilter(value: ResourceStr, error?: (value: string) => void)
Sets the regular expression for input filtering. Only inputs that comply with the regular expression can be displayed. Other inputs are filtered out.
For single-character input scenarios, only single-character matching is supported; for multi-character input scenarios (such as pasting), string matching is supported.
Starting from API version 11, setting inputFilter with a non-empty string invalidates the text filtering effect attached to the type API.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.ArkUI.ArkUI.Full
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| value | ResourceStr | Yes | Regular expression. |
| error | (value: string) => void | No | Filtered-out content to return when regular expression matching fails. No return when regular expression matching succeeds. |
copyOption9+
copyOption(value: CopyOptions)
Sets whether the input text can be copied. If this attribute is set to CopyOptions.None, only paste and select all operations are supported.
If this attribute is set to CopyOptions.None, drag and drop operations are not supported.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.ArkUI.ArkUI.Full
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| value | CopyOptions | Yes | Whether the input text can be copied. Default value: CopyOptions.LocalDevice |
maxLength10+
maxLength(value: number)
Sets the maximum number of characters for text input. By default, there is no maximum number of characters. When the maximum number is reached, no more characters can be entered.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.ArkUI.ArkUI.Full
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| value | number | Yes | Maximum number of characters for text input. Values less than 0 are treated as the default value, meaning no limit is set. Default value: uint32_max (i.e., 2^32-1) |
showCounter10+
showCounter(value: boolean, options?: InputCounterOptions)
Sets the character counter displayed when the number of characters entered exceeds the threshold. If the showCounter API is not called, the character counter is not displayed by default.
options can be set only when value is set to true, in which case a character counter is displayed below the text box. This attribute must be used together with maxLength. The character counter is displayed in this format: Number of characters entered/Character limit.
It is visible when the number of characters entered is greater than the character limit multiplied by the threshold percentage value. If options is not set, the text box border and character counter subscript turn red when the number of characters entered reaches the limit. If value is set to true and options is set, the text box border and character counter subscript turn red and the text box shakes when the number of characters entered reaches the limit, provided that the value of thresholdPercentage is valid. If highlightBorder is set to false, the text box border does not turn red. By default, highlightBorder is set to true. The character counter is not displayed for text boxes in inline input style.
Example 2: Implementing a Counter shows the effect of setting showCounter.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.ArkUI.ArkUI.Full
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| value | boolean | Yes | Whether to display the character counter. true: Character counter is displayed. false: Character counter is not displayed. |
| options11+ | InputCounterOptions | No | Configuration options for the character counter. |
style10+
style(value: TextContentStyle)
Sets the polymorphic style of the text box. The inline input style is only available for the TextAreaType.NORMAL type.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.ArkUI.ArkUI.Full
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| value | TextContentStyle | Yes | Polymorphic style of the text box. Default value: TextContentStyle.DEFAULT |
enableKeyboardOnFocus10+
enableKeyboardOnFocus(value: boolean)
Sets whether to pop up the soft keyboard when the TextArea component obtains focus in a way other than clicking.
Since API version 10, the TextArea component is bound to the input method by default when it obtains focus.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.ArkUI.ArkUI.Full
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| value | boolean | Yes | Whether to pop up the soft keyboard when the TextArea component obtains focus in a way other than clicking. true: The soft keyboard pops up. false: The soft keyboard does not pop up. Default value: true |
selectionMenuHidden10+
selectionMenuHidden(value: boolean)
Sets whether to hide the system text selection menu.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.ArkUI.ArkUI.Full
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| value | boolean | Yes | Whether to hide the system text selection menu. true: The system text selection menu does not appear under the following circumstances: clicking the text box cursor, long-pressing the text box, double-tapping the text box, triple-tapping the text box, or right-clicking the text box. false: The system text selection menu appears under the following circumstances: clicking the text box cursor, long-pressing the text box, double-tapping the text box, triple-tapping the text box, or right-clicking the text box. Default value: false |
barState10+
barState(value: BarState)
Sets the scrollbar display mode.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.ArkUI.ArkUI.Full
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| value | BarState | Yes | Scrollbar display mode. Default value: BarState.Auto |
maxLines10+
maxLines(value: number)
Sets the maximum number of lines that can be displayed. When textOverflow is set, text is truncated if the content exceeds this limit. When textOverflow is not set, in inline style, the text is scrollable if the content exceeds the limit while the text box is focused; maxLines does not apply when the text box is not focused. In non-inline style, the text is truncated according to the number of lines.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.ArkUI.ArkUI.Full
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| value | number | Yes | Maximum number of lines that can be displayed with the inline style in the editing state. Default value: 3. In non-inline style, the default value is UINT32_MAX. Value range: (0, UINT32_MAX] |
maxLines20+
maxLines(lines: number, options: MaxLinesOptions)
Sets the maximum number of visible lines when used with textOverflow. Excess content can be truncated or made scrollable based on configuration. Without textOverflow:
- With focus in inline mode: Text exceeding the maxLines limit becomes scrollable.
- Without focus in inline mode: maxLines has no effect.
Atomic service API: This API can be used in atomic services since API version 20.
System capability: SystemCapability.ArkUI.ArkUI.Full
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| lines | number | Yes | Maximum number of lines that can be displayed with the inline style in the editing state. Default value: 3 with the inline style; +∞ with the non-inline style, indicating that there is no maximum number of lines Value range: (0, +∞) |
| options | MaxLinesOptions | Yes | Display effect for overflow text. Default value: MaxLinesMode.CLIP. |
minLines20+
minLines(lines: Optional<number>)
Sets the minimum number of lines displayed for the component. When constraintSize is set, the component's final height respects the defined constraints.
Atomic service API: This API can be used in atomic services since API version 20.
System capability: SystemCapability.ArkUI.ArkUI.Full
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| lines | Optional<number> | Yes | Minimum number of lines. Default value: 1 Value range: [1, INT32_MAX] Values less than 1 are treated as the default value. |
customKeyboard10+
customKeyboard(value: CustomBuilder | ComponentContent | undefined, options?: KeyboardOptions)
Sets the custom keyboard.
When a custom keyboard is set, activating the text box opens the specified custom component, instead of the system input method.
The height of the custom keyboard can be set using the height property of the custom component's root node, while the width uses the system default value.
The custom keyboard is presented by overlaying the original screen, which is not compressed or lifted if avoid mode is not enabled or avoidance is not needed for the text box.
The custom keyboard cannot obtain the focus, but it blocks gesture events.
By default, the custom keyboard is closed when the input component loses the focus. You can also use the TextAreaController.stopEditing API to close the keyboard.
When setting a custom keyboard, you can bind the onKeyPrelme event to prevent input from the physical keyboard.
From API version 23, the setCustomKeyboardContinueFeature API can be used to enable the continuation feature for custom keyboards. When switching between custom keyboards, the system changes the keyboard directly without triggering the close and open animations.
NOTE
This API cannot be called within attributeModifier.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.ArkUI.ArkUI.Full
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| value | CustomBuilder | ComponentContent22+ | undefined22+ | Yes | Custom keyboard. If the value is undefined, the custom keyboard is closed. |
| options12+ | KeyboardOptions | No | Whether to support keyboard avoidance. |
type11+
type(value: TextAreaType)
Sets the text box type.
Different TextAreaType values trigger corresponding keyboard types and enforce input restrictions.
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.ArkUI.ArkUI.Full
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| value | TextAreaType | Yes | Text box type. Default value: TextAreaType.NORMAL. |
enterKeyType11+
enterKeyType(value: EnterKeyType)
Sets the type of the Enter key.
NOTE
This API can be called within attributeModifier since API version 12.
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.ArkUI.ArkUI.Full
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| value | EnterKeyType | Yes | Type of the Enter key. Default value: EnterKeyType.NEW_LINE |
enableAutoFill12+
enableAutoFill(value: boolean)
Sets whether to enable autofill.
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.ArkUI.ArkUI.Full
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| value | boolean | Yes | Whether to enable autofill. true to enable, false otherwise. Default value: true |
enableSelectedDataDetector22+
enableSelectedDataDetector(enable: boolean | undefined)
Sets whether to enable entity recognition for selected text. This API only works on devices that provide text recognition.
When enableSelectedDataDetector is set to true, all entity types are recognized by default.
This feature is only effective when CopyOptions is set to CopyOptions.LocalDevice or CopyOptions.CrossDevice.
Atomic service API: This API can be used in atomic services since API version 22.
System capability: SystemCapability.ArkUI.ArkUI.Full
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| enable | boolean | undefined | Yes | Whether to enable entity recognition for selected text. true: Entity recognition is enabled. false: Entity recognition is disabled. Default value: true |
contentType12+
contentType(contentType: ContentType)
Sets the content type for autofill.
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.ArkUI.ArkUI.Full
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| contentType | ContentType | Yes | Content type for autofill. |
lineHeight12+
lineHeight(value: number | string | Resource)
Text line height. If the value is less than or equal to 0, the line height is not limited and the font size is adaptive.
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.ArkUI.ArkUI.Full
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| value | number | string | Resource | Yes | Text line height. String type. Specifies the length pixel unit explicitly, for example, '10px', or provides the length in percentage, for example, '100%'. Note: If no pixel unit is specified, the default unit is fp, in which case '10' is equivalent to 10 fp. |
NOTE
If certain characters have significantly taller glyphs than others on the same line, layout anomalies such as clipping, overlap, or misalignment may occur. In this case, adjust component attributes such as height and line height to ensure proper layout rendering.
decoration12+
decoration(value: TextDecorationOptions)
Sets the color, type, and style of the text decorative line.
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.ArkUI.ArkUI.Full
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| value | TextDecorationOptions | Yes | Text decorative line options. Default value: { type: TextDecorationType.None, color: Color.Black, style: TextDecorationStyle.SOLID } |
NOTE
When the bottom contour of a character intersects with the decoration, underline avoidance is triggered, commonly affecting characters like "g", "j", "y", "q", and "p."
If the decoration color is set to Color.Transparent, it inherits the text color of the first character in each line. If the decoration color is set to "#00FFFFFF", the line becomes fully transparent.
letterSpacing12+
letterSpacing(value: number | string | Resource)
Sets the letter spacing for a text style. Percentage values follow default display behavior. If the value specified is 0, the default value is used. For the string type, numeric string values with optional units, for example, "10" or "10fp", are supported.
If the value specified is a negative value, the text is compressed. A negative value too small may result in the text being compressed to 0 and no content being displayed.
This setting applies to every character, including those at line endings.
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.ArkUI.ArkUI.Full
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| value | number | string | Resource | Yes | Letter spacing. Unit: fp |
fontFeature12+
fontFeature(value: string)
Sets the font feature, for example, monospaced digits.
Format: normal | <feature-tag-value>
Format of <feature-tag-value>: <string> [ <integer> | on | off ]
There can be multiple <feature-tag-value> values, which are separated by commas (,).
For example, the input format for monospaced clock fonts is "ss01" on.
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.ArkUI.ArkUI.Full
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| value | string | Yes | Font feature. |
For details about the supported font features, see the font feature list.
Font features are advanced typographic features, such as ligatures and monospace, for OpenType fonts. They are typically used in custom fonts and require the support of the font itself.
For more information about the font features, see the font-feature-settings property and The Complete CSS Demo for OpenType Features.
wordBreak12+
wordBreak(value: WordBreak)
Sets the word break rule. This attribute does not take effect for the placeholder text.
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.ArkUI.ArkUI.Full
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| value | WordBreak | Yes | Word break rule. Default value: WordBreak.BREAK_WORD |
NOTE
The component does not support the clip attribute. Therefore, setting this attribute does not affect text clipping.
selectedBackgroundColor12+
selectedBackgroundColor(value: ResourceColor)
Sets the background color of the selected text. If the opacity is not set, a 20% opacity will be used.
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.ArkUI.ArkUI.Full
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| value | ResourceColor | Yes | Background color of the selected text. |
caretStyle12+
caretStyle(value: CaretStyle)
Sets the caret style.
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.ArkUI.ArkUI.Full
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| value | CaretStyle | Yes | Caret style. |
NOTE
When both caretColor and the color parameter in caretStyle are configured, the last-set value takes precedence.
Since API version 12, this API can be used to set the text handle color, which is the same as the caret color.
textIndent12+
textIndent(value: Dimension)
Sets the indent of the first line text.
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.ArkUI.ArkUI.Full
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| value | Dimension | Yes | Indent of the first line text. Default value: 0 |
textOverflow12+
textOverflow(value: TextOverflow)
Sets the display mode when the text is too long.
In inline style, the effect of truncating text according to maxLines only applies when textOverflow is set.
Text is clipped at the transition between words. To clip text in the middle of a word, set wordBreak to WordBreak.BREAK_ALL.
If textOverflow is set to TextOverflow.None, TextOverflow.Clip, or TextOverflow.Ellipsis, this attribute must be used with maxLines for the settings to take effect. TextOverflow.None produces the same effect as TextOverflow.Clip.
NOTE
The TextArea component does not support the TextOverflow.MARQUEE mode. If this attribute is set to TextOverflow.MARQUEE, TextOverflow.Clip is used instead.
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.ArkUI.ArkUI.Full
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| value | TextOverflow | Yes | Display mode when the text is too long. Default value: TextOverflow.Clip |
minFontSize12+
minFontSize(value: number | string | Resource)
Sets the minimum font size. For the string type, numeric string values with optional units, for example, "10" or "10fp", are supported.
For the setting to take effect, this attribute must be used together with maxFontSize and maxLines, or layout constraint settings.
When the adaptive font size is used, the fontSize settings do not take effect.
If the value of minFontSize is less than or equal to 0, the adaptive font sizing feature is disabled. In such cases, the fontSize attribute is used instead. If fontSize is not explicitly set, its default value will apply.
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.ArkUI.ArkUI.Full
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| value | number | string | Resource | Yes | Minimum font size. Unit: fp |
maxFontSize12+
maxFontSize(value: number | string | Resource)
Sets the maximum font size. For the string type, numeric string values with optional units, for example, "10" or "10fp", are supported.
For the setting to take effect, this attribute must be used together with minFontSize and maxLines, or layout constraint settings.
When the adaptive font size is used, the fontSize settings do not take effect.
If the value of maxFontSize is less than or equal to 0 or is less than the value of minFontSize, the adaptive font sizing feature is disabled. In such cases, the fontSize attribute is used instead. If fontSize is not explicitly set, its default value will apply.
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.ArkUI.ArkUI.Full
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| value | number | string | Resource | Yes | Maximum font size. Unit: fp |
heightAdaptivePolicy12+
heightAdaptivePolicy(value: TextHeightAdaptivePolicy)
Sets how the adaptive height is determined for the text.
When this attribute is set to TextHeightAdaptivePolicy.MAX_LINES_FIRST, the maxLines attribute takes precedence for adjusting the text height. If the maxLines setting results in a layout beyond the layout constraints, the text will shrink to a font size between minFontSize and maxFontSize to allow for more content to be shown.
If the text box is in inline input style, the font size in the editing state is different from that in the non-editing state.
If this attribute is set to TextHeightAdaptivePolicy.MIN_FONT_SIZE_FIRST, the minFontSize attribute takes precedence for adjusting the text height. If the text can fit in one line with the minFontSize setting, the text will enlarge to the largest possible font size between minFontSize and maxFontSize.
If this attribute is set to TextHeightAdaptivePolicy.LAYOUT_CONSTRAINT_FIRST, the layout constraints take precedence for adjusting the text height. If the resultant layout is beyond the layout constraints, the text will shrink to a font size between minFontSize and maxFontSize to respect the layout constraints.
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.ArkUI.ArkUI.Full
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| value | TextHeightAdaptivePolicy | Yes | How the adaptive height is determined for the text. Default value: TextHeightAdaptivePolicy.MAX_LINES_FIRST |
lineSpacing12+
lineSpacing(value: LengthMetrics)
Sets the line spacing of the text. If the value specified is less than or equal to 0, the default value 0 is used.
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.ArkUI.ArkUI.Full
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| value | LengthMetrics | Yes | Line spacing. Default value: 0 |
lineSpacing20+
lineSpacing(value: LengthMetrics, options?: LineSpacingOptions)
Sets the line spacing for text. When LineSpacingOptions is not specified, line spacing is applied above the first line and below the last line by default.
Atomic service API: This API can be used in atomic services since API version 20.
System capability: SystemCapability.ArkUI.ArkUI.Full
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| value | LengthMetrics | Yes | Line spacing. Values less than or equal to 0 are treated as the default value 0. |
| options | LineSpacingOptions | No | Line spacing configuration options. Default value: { onlyBetweenLines: false }. |
lineBreakStrategy12+
lineBreakStrategy(strategy: LineBreakStrategy)
Sets the line break rule. This attribute takes effect only when wordBreak is not WordBreak.BREAK_ALL. Hyphens are not supported.
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.ArkUI.ArkUI.Full
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| strategy | LineBreakStrategy | Yes | Line break rule. Default value: LineBreakStrategy.GREEDY |
editMenuOptions12+
editMenuOptions(editMenu: EditMenuOptions)
Sets the extended options of the custom context menu on selection, including the text content, icon, and callback.
When disableMenuItems or disableSystemServiceMenuItems is used to disable system service menu items in the context menu on selection, the disabled menu options will be excluded from the parameter list in the onCreateMenu callback of editMenuOptions.
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.ArkUI.ArkUI.Full
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| editMenu | EditMenuOptions | Yes | Extended options of the custom context menu on selection. |
enablePreviewText12+
enablePreviewText(enable: boolean)
Sets whether to enable preview text.
The preview content is defined as a temporary, uncommitted input state. Currently, the text interception function is not supported.
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.ArkUI.ArkUI.Full
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| enable | boolean | Yes | Whether to enable preview text. true: Preview text is enabled. false: Preview text is disabled. Default value: true |
NOTE
Preview text represents a temporary, uncommitted input state. This feature requires support from the input method with pre-commit text functionality enabled. During text entry, when candidate words have not been confirmed yet, the text box displays marked text in a provisional state. For example, when typing Chinese using Pinyin input, the Pinyin letters appear in the input box before selecting from the candidate word list. This intermediate state constitutes preview text.
enableHapticFeedback13+
enableHapticFeedback(isEnabled: boolean)
Specifies whether to enable haptic feedback.
To enable haptic feedback, you must declare the ohos.permission.VIBRATE permission under requestPermissions in the module.json5 file of the project.
"requestPermissions": [
{
"name": "ohos.permission.VIBRATE",
}
]
Atomic service API: This API can be used in atomic services since API version 13.
System capability: SystemCapability.ArkUI.ArkUI.Full
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| isEnabled | boolean | Yes | Whether to enable haptic feedback. true to enable, false otherwise. Default value: true |
autoCapitalizationMode20+
autoCapitalizationMode(mode: AutoCapitalizationMode)
Sets the auto-capitalization text mode. This API provides the capability, but actual implementation depends on the input method application.
Atomic service API: This API can be used in atomic services since API version 20.
System capability: SystemCapability.ArkUI.ArkUI.Full
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| mode | AutoCapitalizationMode | Yes | Auto-capitalization mode. The default state is inactive. |
keyboardAppearance15+
keyboardAppearance(appearance: Optional<KeyboardAppearance>)
Sets the keyboard appearance for the text box. This setting takes effect only after input method adaptation. For details, see Immersive Mode of the Input Method Application.
Atomic service API: This API can be used in atomic services since API version 15.
System capability: SystemCapability.ArkUI.ArkUI.Full
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| appearance | Optional<KeyboardAppearance> | Yes | Appearance of the keyboard. Default value: KeyboardAppearance.NONE_IMMERSIVE |
strokeWidth20+
strokeWidth(width: Optional<LengthMetrics>)
Sets the text stroke width.
Atomic service API: This API can be used in atomic services since API version 20.
System capability: SystemCapability.ArkUI.ArkUI.Full
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| width | Optional<LengthMetrics> | Yes | Text stroke width. When the unit of LengthMetrics is px: Values < 0: solid text. Values > 0: outlined text. Default value: 0 (no stroke) |
strokeColor20+
strokeColor(color: Optional<ResourceColor>)
Sets the text stroke color.
Atomic service API: This API can be used in atomic services since API version 20.
System capability: SystemCapability.ArkUI.ArkUI.Full
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| color | Optional<ResourceColor> | Yes | Stroke color. Default value: font color. Invalid values are treated as the default value. |
stopBackPress15+
stopBackPress(isStopped: Optional<boolean>)
Sets whether to prevent the back key event from being propagated.
Atomic service API: This API can be used in atomic services since API version 15.
System capability: SystemCapability.ArkUI.ArkUI.Full
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| isStopped | Optional<boolean> | Yes | Whether to prevent the back button press from being propagated to other components or applications. true: Propagation is prevented. false: Propagation is allowed. Default value: true The default value is used for abnormal values. |
halfLeading18+
halfLeading(halfLeading: Optional<boolean>)
Enables half leading for text, which splits the leading equally between the top and bottom of the line.
Atomic service API: This API can be used in atomic services since API version 18.
System capability: SystemCapability.ArkUI.ArkUI.Full
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| halfLeading | Optional<boolean> | Yes | Whether half leading is enabled. Half leading refers to splitting the leading in half and applying it equally to the top and bottom of the line. true: Half leading is enabled. false: Half leading is not enabled. Default value: false |
minFontScale18+
minFontScale(scale: Optional<number | Resource>)
Sets the minimum font scale factor for text.
Atomic service API: This API can be used in atomic services since API version 18.
System capability: SystemCapability.ArkUI.ArkUI.Full
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| scale | Optional<number | Resource> | Yes | Minimum font scale factor for text. The undefined type is supported. Value range: [0, 1] NOTE A value less than 0 is handled as 0. A value greater than 1 is handled as 1. Abnormal values are ineffective by default. Before use, the configuration.json file and app.json5 file must be configured in the project. For details, see Example 17: Setting the Minimum and Maximum Font Scale Factors. |
maxFontScale18+
maxFontScale(scale: Optional<number | Resource>)
Sets the maximum font scale factor for text.
Atomic service API: This API can be used in atomic services since API version 18.
System capability: SystemCapability.ArkUI.ArkUI.Full
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| scale | Optional<number | Resource> | Yes | Maximum font scale factor for text. The undefined type is supported. Value range: [1, +∞) NOTE Values less than 1 are treated as 1. Abnormal values are ineffective by default. Before use, the configuration.json file and app.json5 file must be configured in the project. For details, see Example 17: Setting the Minimum and Maximum Font Scale Factors. |
ellipsisMode18+
ellipsisMode(mode: Optional<EllipsisMode>)
Sets the ellipsis position. For the settings to work, textOverflow must be set to TextOverflow.Ellipsis and maxLines must be specified. Setting ellipsisMode alone does not take effect.
EllipsisMode.START and EllipsisMode.CENTER take effect only when maxLines is set to 1.
Atomic service API: This API can be used in atomic services since API version 18.
System capability: SystemCapability.ArkUI.ArkUI.Full
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| mode | Optional<EllipsisMode> | Yes | Ellipsis position. Default value: EllipsisMode.END |
enableAutoSpacing20+
enableAutoSpacing(enabled: Optional<boolean>)
Sets whether to enable automatic spacing between Chinese and Western characters.
Atomic service API: This API can be used in atomic services since API version 20.
System capability: SystemCapability.ArkUI.ArkUI.Full
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| enabled | Optional<boolean> | Yes | Whether to enable automatic spacing between Chinese and Western characters. true to enable, false otherwise. Default value: false |
scrollBarColor22+
scrollBarColor(thumbColor: ColorMetrics | undefined)
Sets the color of the scrollbar.
Atomic service API: This API can be used in atomic services since API version 22.
System capability: SystemCapability.ArkUI.ArkUI.Full
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| thumbColor | ColorMetrics | undefined | Yes | Scrollbar color. Default value: '#66182431', displayed as gray. |
compressLeadingPunctuation23+
compressLeadingPunctuation(enabled: Optional<boolean>)
Sets whether to enable leading punctuation compression.
NOTE
Leading punctuation is not compressed by default.
For the list of punctuation marks that support compression, see the punctuation range at the beginning of a line in ParagraphStyle.
Atomic service API: This API can be used in atomic services since API version 23.
System capability: SystemCapability.ArkUI.ArkUI.Full
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| enabled | Optional<boolean> | Yes | Whether to enable leading punctuation compression. true: Leading punctuation compression is enabled. false: Leading punctuation compression is disabled. |
includeFontPadding23+
includeFontPadding(include: Optional<boolean>)
Sets whether to add spacing to the first and last lines to avoid text truncation. If this attribute is not set, no spacing is added by default.
Atomic service API: This API can be used in atomic services since API version 23.
System capability: SystemCapability.ArkUI.ArkUI.Full
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| include | Optional<boolean> | Yes | Whether to add spacing to the first and last lines to avoid text truncation. true: Spacing is added to the first and last lines. false: Spacing is not added to the first and last lines. |
fallbackLineSpacing23+
fallbackLineSpacing(enabled: Optional<boolean>)
Adapts the line height to the actual text height for overlapped multi-line text. This API takes effect only when the line height is less than the actual text height. If this API is not set, the line height does not adapt to the actual text height by default.
Atomic service API: This API can be used in atomic services since API version 23.
System capability: SystemCapability.ArkUI.ArkUI.Full
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| enabled | Optional<boolean> | Yes | Whether the line height is adapted to the actual text height. true: Line height is adapted to the actual text height. false: Line height is not adapted to the actual text height. |
selectedDragPreviewStyle23+
selectedDragPreviewStyle(value: SelectedDragPreviewStyle | undefined)
Sets the drag preview style for text being dragged in the multi-line text box.
Atomic service API: This API can be used in atomic services since API version 23.
System capability: SystemCapability.ArkUI.ArkUI.Full
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| value | SelectedDragPreviewStyle | undefined | Yes | Drag preview style for text being dragged in the multi-line text box. If this parameter is set to undefined, the drag preview follows the theme: white in light mode and black in dark mode. |
Events
In addition to the universal events, the following events are supported.
onChange
onChange(callback: EditableTextOnChangeCallback)
Called when the input in the text box changes.
In this callback, if caret operations are performed, you must adjust the caret logic based on the previewText parameter of EditableTextOnChangeCallback to ensure it works seamlessly within the preview display scenario.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.ArkUI.ArkUI.Full
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| callback | EditableTextOnChangeCallback | Yes | Callback invoked when the input in the text box changes. |
onEditChange10+
onEditChange(callback: (isEditing: boolean) => void)
Called when the input state changes. The text box is in the editing state when it has the caret placed in it, and is in the non-editing state otherwise.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.ArkUI.ArkUI.Full
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| isEditing | boolean | Yes | Whether the component is in the editing state. true: Editing state. false: Non-editing state. |
onCopy8+
onCopy(callback: (value: string) => void)
Called when a copy operation is performed.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.ArkUI.ArkUI.Full
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| value | string | Yes | Text that is copied. |
onCut8+
onCut(callback: (value: string) => void)
Called when a cut operation is performed.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.ArkUI.ArkUI.Full
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| value | string | Yes | Text that is cut. |
onPaste
onPaste(callback: (value: string, event: PasteEvent) => void)
Called when a paste operation is performed.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.ArkUI.ArkUI.Full
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| value | string | Yes | Text to be pasted. |
| event11+ | PasteEvent | Yes | Custom paste event. |
onTextSelectionChange10+
onTextSelectionChange(callback: (selectionStart: number, selectionEnd: number) => void)
Called when the text selection changes or the caret position changes during editing.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.ArkUI.ArkUI.Full
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| selectionStart | number | Yes | Start position of the selected text. The start position of text is 0. |
| selectionEnd | number | Yes | End position of the selected text. |
onContentScroll10+
onContentScroll(callback: (totalOffsetX: number, totalOffsetY: number) => void)
Called when the text content is scrolled.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.ArkUI.ArkUI.Full
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| totalOffsetX | number | Yes | Horizontal offset of the text within the content area. Unit: px |
| totalOffsetY | number | Yes | Vertical offset of the text within the content area. Unit: px |
onSubmit11+
onSubmit(callback: (enterKey: EnterKeyType) => void)
Called when the Enter key on the soft keyboard is pressed.
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.ArkUI.ArkUI.Full
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| enterKey | EnterKeyType | Yes | Type of the Enter key. If it is EnterKeyType.NEW_LINE and the text box is in inline input style, onSubmit is not triggered. |
onSubmit14+
onSubmit(callback: TextAreaSubmitCallback)
Called when the Enter key on the soft keyboard is pressed, providing methods to maintain the editing state of the TextArea component upon submission.
Atomic service API: This API can be used in atomic services since API version 14.
System capability: SystemCapability.ArkUI.ArkUI.Full
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| callback | TextAreaSubmitCallback | Yes | Called when the Enter key on the soft keyboard is pressed. |
onWillInsert12+
onWillInsert(callback: Callback<InsertValue, boolean>)
Called when text is about to be inserted.
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.ArkUI.ArkUI.Full
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| callback | Callback<InsertValue, boolean> | Yes | Callback invoked when text is about to be inserted. It returns true if the text is inserted; returns false otherwise. This callback is not invoked for pre-edit or candidate word operations. It is available only for system input methods. |
onDidInsert12+
onDidInsert(callback: Callback<InsertValue>)
Called when text is inserted.
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.ArkUI.ArkUI.Full
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| callback | Callback<InsertValue> | Yes | Callback triggered when text is inserted. It is available only for system input methods. |
onWillDelete12+
onWillDelete(callback: Callback<DeleteValue, boolean>)
Called when text is about to be deleted.
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.ArkUI.ArkUI.Full
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| callback | Callback<DeleteValue, boolean> | Yes | Callback invoked when text is about to be deleted. It returns true if the text is deleted; returns false otherwise. This callback is not invoked for text preview. It is available only for system input methods. |
onDidDelete12+
onDidDelete(callback: Callback<DeleteValue>)
Called when text is deleted.
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.ArkUI.ArkUI.Full
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| callback | Callback<DeleteValue> | Yes | Callback triggered when text is deleted. It is available only for system input methods. |
NOTE
Clicking the clear button does not trigger the onDidDelete callback.
onWillChange15+
onWillChange(callback: Callback<EditableTextChangeValue, boolean>)
Called when the text content is about to change.
This callback is triggered after onWillInsert and onWillDelete, but before onDidInsert and onDidDelete.
Atomic service API: This API can be used in atomic services since API version 15.
System capability: SystemCapability.ArkUI.ArkUI.Full
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| callback | Callback<EditableTextChangeValue, boolean> | Yes | Callback triggered when the text content is about to change. true: The change is allowed. false: The change is canceled. |
onWillAttachIME22+
onWillAttachIME(callback: Callback<IMEClient> | undefined)
Called when the input box is about to be bound to an input method.
Before the input box is bound to an input method, you can use the setKeyboardAppearanceConfig API of UIContext to set the keyboard style.
From API version 22, the setExtraConfig method of IMEClient can be called to set input method extension information. After the input method is bound, it receives this extension information which can be used to implement custom functionality.
IMEClient is valid only during the execution of onWillAttachIME and cannot be called asynchronously.
Atomic service API: This API can be used in atomic services since API version 22.
System capability: SystemCapability.ArkUI.ArkUI.Full
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| callback | Callback<IMEClient> | undefined | Yes | Callback invoked when the input box is about to be bound to an input method. |
TextAreaController8+
The controller for the TextArea component inherits from TextContentControllerBase. The APIs involved are as follows: system API getText and other APIs like getTextContentRect, getTextContentLineCount, getCaretOffset, addText, deleteText, getSelection, clearPreviewText, setStyledPlaceholder, and deleteBackward.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.ArkUI.ArkUI.Full
Objects to Import
controller: TextAreaController = new TextAreaController()
constructor8+
constructor()
A constructor used to create a TextAreaController object.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.ArkUI.ArkUI.Full
caretPosition8+
caretPosition(value: number): void
Sets the position of the caret.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.ArkUI.ArkUI.Full
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| value | number | Yes | Length from the start of the string to the position where the caret is located. Values less than 0 are treated as 0. Values greater than the string length are treated as the string length. |
setTextSelection10+
setTextSelection(selectionStart: number, selectionEnd: number, options?: SelectionOptions): void
Sets the text selection range and highlights the selected text when the component is focused. This API works only when the value of selectionStart is less than that of selectionEnd.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.ArkUI.ArkUI.Full
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| selectionStart | number | Yes | Start position of the text selection range. The start position of text in the text box is 0. Values less than 0 are treated as 0. Values greater than the maximum text length are treated as the maximum text length. Atomic service API: This API can be used in atomic services since API version 11. |
| selectionEnd | number | Yes | End position of the text selection range. Values less than 0 are treated as 0. Values greater than the maximum text length are treated as the maximum text length. Atomic service API: This API can be used in atomic services since API version 11. |
| options12+ | SelectionOptions | No | Configuration options for text selection. Default value: MenuPolicy.DEFAULT Atomic service API: This API can be used in atomic services since API version 12. |
NOTE
If selectionMenuHidden is set to true or a 2-in-1 device is used, calling setTextSelection does not display the context menu even when options is set to MenuPolicy.SHOW.
If the selected text contains an emoji, the emoji is selected when its start position is within the text selection range.
stopEditing10+
stopEditing(): void
Exits the editing state.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.ArkUI.ArkUI.Full
TextAreaType11+
Multi-line text input box type.
System capability: SystemCapability.ArkUI.ArkUI.Full
| Name | Value | Description |
|---|---|---|
| NORMAL | 0 | Basic input mode with no special restrictions. Atomic service API: This API can be used in atomic services since API version 12. |
| NUMBER | 2 | Digit input mode. Atomic service API: This API can be used in atomic services since API version 12. |
| PHONE_NUMBER | 3 | Phone number input mode. In this mode, the following characters are allowed: digits, spaces, plus signs (+), hyphens (-), asterisks (*), and number signs (#); the length is not limited. Atomic service API: This API can be used in atomic services since API version 12. |
| 5 | Email address input mode. This mode accepts only digits, letters, underscores (_), dots (.), and the following special characters: ! # $ % & ' * + - / = ? ^ ` { | } ~ @ (which can only appear once) Atomic service API: This API can be used in atomic services since API version 12. |
|
| NUMBER_DECIMAL12+ | 12 | Decimal number input mode. The value can contain digits and one decimal point. Atomic service API: This API can be used in atomic services since API version 12. |
| URL12+ | 13 | URL input mode with no special restrictions. Atomic service API: This API can be used in atomic services since API version 12. |
| ONE_TIME_CODE20+ | 14 | One-time code (verification code) input mode with no special restrictions. Atomic service API: This API can be used in atomic services since API version 20. |
TextAreaSubmitCallback14+
type TextAreaSubmitCallback = (enterKeyType: EnterKeyType, event?: SubmitEvent) => void
Represents the callback invoked when the Enter key on the soft keyboard is pressed.
Atomic service API: This API can be used in atomic services since API version 14.
System capability: SystemCapability.ArkUI.ArkUI.Full
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| enterKeyType | EnterKeyType | Yes | Type of the Enter key. If the type is EnterKeyType.NEW_LINE, onSubmit is not triggered. |
| event | SubmitEvent | No | Submit event. |
Example
Example 1: Setting and Obtaining the Cursor Position
This example shows how to set and obtain the caret position using controller, available since API version 8.
// xxx.ets
@Entry
@Component
struct TextAreaExample {
@State text: string = '';
@State positionInfo: CaretOffset = { index: 0, x: 0, y: 0 };
controller: TextAreaController = new TextAreaController();
build() {
Column() {
TextArea({
text: this.text,
placeholder: 'The text area can hold an unlimited amount of text. input your word...',
controller: this.controller
})
.placeholderFont({ size: 16, weight: 400 })
.width(336)
.height(56)
.margin(20)
.fontSize(16)
.fontColor('#182431')
.backgroundColor('#FFFFFF')
.onChange((value: string) => {
this.text = value;
})
Text(this.text)
Button('Set caretPosition 1')
.backgroundColor('#007DFF')
.margin(15)
.onClick(() => {
// Move the caret to after the first entered character.
this.controller.caretPosition(1);
})
Button('Get CaretOffset')
.backgroundColor('#007DFF')
.margin(15)
.onClick(() => {
this.positionInfo = this.controller.getCaretOffset();
})
}.width('100%').height('100%').backgroundColor('#F1F3F5')
}
}

Example 2: Implementing a Counter
This example demonstrates how to implement the character counter functionality using the maxLength and showCounter attributes, both available since API version 10.
// xxx.ets
@Entry
@Component
struct TextAreaExample {
@State text: string = '';
controller: TextAreaController = new TextAreaController();
build() {
Column() {
TextArea({
text: this.text,
placeholder: 'The text area can hold an unlimited amount of text. input your word...',
controller: this.controller
})
.placeholderFont({ size: 16, weight: 400 })
.width(336)
.height(56)
.margin(20)
.fontSize(16)
.fontColor('#182431')
.backgroundColor('#FFFFFF')
.maxLength(4)
.showCounter(true, { thresholdPercentage: 50, highlightBorder: true })
// The character counter is in this format: Number of characters that have been entered/Maximum number of characters allowed, which is specified by maxLength().
// The character counter is displayed when the number of characters that have been entered is greater than the maximum number of characters multiplied by 50% (threshold percentage).
// When highlightBorder is set to false, the text box border does not turn red when the input exceeds the maximum character limit. The default value is true.
.onChange((value: string) => {
this.text = value;
})
}.width('100%').height('100%').backgroundColor('#F1F3F5')
}
}

Example 3: Implementing a Custom Keyboard
This example implements a custom keyboard using the customKeyboard attribute (available since API version 10) to set the input parameter type in value to CustomBuilder and ComponentContent.
Since API version 22, ComponentContent is added to the input parameter type of customKeyboard.
// xxx.ets
import { ComponentContent } from '@kit.ArkUI';
class BuilderParams {
inputValue: string;
controller: TextAreaController;
constructor(inputValue: string, controller: TextAreaController) {
this.inputValue = inputValue;
this.controller = controller;
}
}
@Builder
function CustomKeyboardBuilder(builderParams: BuilderParams) {
Column() {
Row() {
Button('x').onClick(() => {
// Disable the custom keyboard.
builderParams.controller.stopEditing();
}).margin(10)
}
Grid() {
ForEach([1, 2, 3, 4, 5, 6, 7, 8, 9, '*', 0, '#'], (item: number | string) => {
GridItem() {
Button(item + "")
.width(110).onClick(() => {
builderParams.inputValue += item;
})
}
})
}.maxCount(3).columnsGap(10).rowsGap(10).padding(5)
}.backgroundColor(Color.Gray)
}
@Entry
@Component
struct TextAreaExample {
controller: TextAreaController = new TextAreaController();
@State inputValue: string = "";
@State componentContent ?: ComponentContent<BuilderParams> = undefined;
@State builderParam: BuilderParams = new BuilderParams(this.inputValue, this.controller);
@State supportAvoidance: boolean = true;
aboutToAppear(): void {
// Create a ComponentContent instance.
this.componentContent = new ComponentContent(this.getUIContext(), wrapBuilder(CustomKeyboardBuilder), this.builderParam);
}
build(){
Column() {
Text('Builder').margin(10).border({ width: 1 })
TextArea({ controller: this.builderParam.controller, text: this.builderParam.inputValue })
.customKeyboard(this.componentContent, { supportAvoidance: this.supportAvoidance })
.margin(10).border({ width: 1 }).height('48vp')
Text('ComponentContent').margin(10).border({ width: 1 })
TextArea({ controller: this.builderParam.controller, text: this.builderParam.inputValue })
.customKeyboard(CustomKeyboardBuilder(this.builderParam), { supportAvoidance: this.supportAvoidance })
.margin(10).border({ width: 1 }).height('48vp')
}
}
}

Example 4: Setting the Enter Key Type
This example shows how to use the enterKeyType attribute, which is supported since API version 11, to dynamically change the effect of the Enter key on the soft keyboard.
// xxx.ets
@Entry
@Component
struct TextAreaExample {
@State text: string = '';
@State enterTypes: Array<EnterKeyType> =
[EnterKeyType.Go, EnterKeyType.Search, EnterKeyType.Send, EnterKeyType.Done, EnterKeyType.Next,
EnterKeyType.PREVIOUS, EnterKeyType.NEW_LINE];
@State index: number = 0;
build() {
Column({ space: 20 }) {
TextArea({ placeholder: 'Enter user name', text: this.text })
.width(380)
.enterKeyType(this.enterTypes[this.index])
.onChange((value: string) => {
this.text = value;
})
.onSubmit((enterKey: EnterKeyType) => {
console.info("trigger area onSubmit" + enterKey);
})
Button('Change EnterKeyType').onClick(() => {
this.index = (this.index + 1) % this.enterTypes.length;
})
}.width('100%')
}
}

Example 5: Setting Text Wrapping Rules
This example demonstrates the effects of different text wrapping rules using the wordBreak attribute, available since API version 12.
// xxx.ets
@Entry
@Component
struct TextAreaExample {
build() {
Column() {
Text("WordBreakType as NORMAL").fontSize(16).fontColor(0xFF0000)
TextArea({
text: 'This is set wordBreak to WordBreak text Taumatawhakatangihangakoauauotamateaturipukakapikimaungahoronukupokaiwhenuakitanatahu.'
})
.fontSize(16)
.border({ width: 1 })
.wordBreak(WordBreak.NORMAL)
Text("WordBreakType as BREAK_ALL").fontSize(16).fontColor(0xFF0000)
TextArea({
text: 'This is set wordBreak to WordBreak text Taumatawhakatangihangakoauauotamateaturipukakapikimaungahoronukupokaiwhenuakitanatahu.'
})
.fontSize(16)
.border({ width: 1 })
.wordBreak(WordBreak.BREAK_ALL)
Text("WordBreakType as BREAK_ALL, Chinese Text").fontSize(16).fontColor(0xFF0000)
TextArea({
text: '多行文本输入框组件,当输入的文本内容超过组件宽度时会自动换行显示。\n高度未设置时,组件无默认高度,自适应内容高度。宽度未设置时,默认撑满最大宽度。'
})
.fontSize(16)
.border({ width: 1 })
.wordBreak(WordBreak.BREAK_ALL)
Text("WordBreakType as BREAK_WORD").fontSize(16).fontColor(0xFF0000)
TextArea({
text: 'This is set wordBreak to WordBreak text Taumatawhakatangihangakoauauotamateaturipukakapikimaungahoronukupokaiwhenuakitanatahu.'
})
.fontSize(16)
.border({ width: 1 })
.wordBreak(WordBreak.BREAK_WORD)
}
}
}

Example 6: Setting the Text Style
This example showcases various text styles by using the lineHeight, letterSpacing, and decoration attributes, which are supported since API version 12.
// xxx.ets
@Entry
@Component
struct TextAreaExample {
build() {
Row() {
Column() {
Text('lineHeight').fontSize(9).fontColor(0xCCCCCC)
TextArea({ text: 'lineHeight unset' })
.border({ width: 1 }).padding(10).margin(5)
TextArea({ text: 'lineHeight 15' })
.border({ width: 1 }).padding(10).margin(5).lineHeight(15)
TextArea({ text: 'lineHeight 30' })
.border({ width: 1 }).padding(10).margin(5).lineHeight(30)
Text('letterSpacing').fontSize(9).fontColor(0xCCCCCC)
TextArea({ text: 'letterSpacing 0' })
.border({ width: 1 }).padding(5).margin(5).letterSpacing(0)
TextArea({ text: 'letterSpacing 3' })
.border({ width: 1 }).padding(5).margin(5).letterSpacing(3)
TextArea({ text: 'letterSpacing -1' })
.border({ width: 1 }).padding(5).margin(5).letterSpacing(-1)
Text('decoration').fontSize(9).fontColor(0xCCCCCC)
TextArea({ text: 'LineThrough, Red\nsecond line' })
.border({ width: 1 }).padding(5).margin(5)
.decoration({ type: TextDecorationType.LineThrough, color: Color.Red })
TextArea({ text: 'Overline, Red, DOTTED\nsecond line' })
.border({ width: 1 }).padding(5).margin(5)
.decoration({ type: TextDecorationType.Overline, color: Color.Red, style: TextDecorationStyle.DOTTED })
TextArea({ text: 'Underline, Red, WAVY\nsecond line' })
.border({ width: 1 }).padding(5).margin(5)
.decoration({ type: TextDecorationType.Underline, color: Color.Red, style: TextDecorationStyle.WAVY })
}.height('90%')
}
.width('90%')
.margin(10)
}
}

Example 7: Setting Text Feature Effects
This example demonstrates how to display text with various typographic features using the fontFeature attribute, available since API version 12.
// xxx.ets
@Entry
@Component
struct TextAreaExample {
@State text1: string = 'This is ss01 on : 0123456789';
@State text2: string = 'This is ss01 off: 0123456789';
build() {
Column() {
TextArea({ text: this.text1 })
.fontSize(20)
.margin({ top: 200 })
.fontFeature("\"ss01\" on")
TextArea({ text: this.text2 })
.margin({ top: 10 })
.fontSize(20)
.fontFeature("\"ss01\" off")
}
.width("90%")
.margin("5%")
}
}

Example 8: Setting Custom Keyboard Avoidance
This example implements the custom keyboard avoidance effect by configuring the KeyboardOptions API (available since API version 12) through the customKeyboard attribute (available since API version 10).
// xxx.ets
@Entry
@Component
struct TextAreaExample {
controller: TextAreaController = new TextAreaController();
@State inputValue: string = "";
@State height1: string | number = '80%';
@State height2: number = 100;
@State supportAvoidance: boolean = true;
// Create a custom keyboard component.
@Builder
CustomKeyboardBuilder() {
Column() {
Row() {
Button('x').onClick(() => {
// Disable the custom keyboard.
this.controller.stopEditing();
}).margin(10)
}
Grid() {
ForEach([1, 2, 3, 4, 5, 6, 7, 8, 9, '*', 0, '#'], (item: number | string) => {
GridItem() {
Button(item + "")
.width(110).onClick(() => {
this.inputValue += item;
})
}
})
}.maxCount(3).columnsGap(10).rowsGap(10).padding(5)
}.backgroundColor(Color.Gray)
}
build() {
Column() {
Row() {
Button("20%")
.fontSize(24)
.onClick(() => {
this.height1 = "20%";
})
Button("80%")
.fontSize(24)
.margin({ left: 20 })
.onClick(() => {
this.height1 = "80%";
})
}
.justifyContent(FlexAlign.Center)
.alignItems(VerticalAlign.Bottom)
.height(this.height1)
.width("100%")
.padding({ bottom: 50 })
TextArea({ controller: this.controller, text: this.inputValue })// Bind the custom keyboard.
.height(100)
.customKeyboard(this.CustomKeyboardBuilder(), { supportAvoidance: this.supportAvoidance })
.margin(10)
.border({ width: 1 })
}
}
}

Example 9: Setting Text Auto-Adaptation
This example shows how to implement adaptive font sizing for text through the minFontSize, maxFontSize, and heightAdaptivePolicy attributes, available since API version 12.
// xxx.ets
@Entry
@Component
struct TextAreaExample {
build() {
Row() {
Column() {
Text('heightAdaptivePolicy').fontSize(9).fontColor(0xCCCCCC)
TextArea({text: 'This is the text with the height adaptive policy set'})
.width('80%').height(90).borderWidth(1).margin(1)
.minFontSize(4)
.maxFontSize(40)
.maxLines(3)
.heightAdaptivePolicy(TextHeightAdaptivePolicy.MAX_LINES_FIRST)
TextArea({text: 'This is the text with the height adaptive policy set'})
.width('80%').height(90).borderWidth(1).margin(1)
.minFontSize(4)
.maxFontSize(40)
.maxLines(3)
.heightAdaptivePolicy(TextHeightAdaptivePolicy.MIN_FONT_SIZE_FIRST)
TextArea({text: 'This is the text with the height adaptive policy set'})
.width('80%').height(90).borderWidth(1).margin(1)
.minFontSize(4)
.maxFontSize(40)
.maxLines(3)
.heightAdaptivePolicy(TextHeightAdaptivePolicy.LAYOUT_CONSTRAINT_FIRST)
}.height('90%')
}
.width('90%')
.margin(10)
}
}

Example 10: Setting the Text Line Spacing
This example demonstrates the display effect of text under different line spacing settings through the lineSpacing attribute, available since API version 12. The onlyBetweenLines property in LineSpacingOptions (available since API version 20) controls whether line spacing applies only between lines.
// xxx.ets
import { LengthMetrics } from '@kit.ArkUI';
@Entry
@Component
struct TextAreaExample {
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start, justifyContent: FlexAlign.SpaceBetween }) {
Text('TextArea lineSpacing.').fontSize(9).fontColor(0xCCCCCC)
TextArea({ text: 'This is the TextArea with no lineSpacing set.' })
.fontSize(12)
TextArea({ text: 'This is the TextArea with lineSpacing set to 20_px.' })
.fontSize(12)
.lineSpacing(LengthMetrics.px(20))
TextArea({ text: 'This is the TextArea with lineSpacing set to 20_vp.' })
.fontSize(12)
.lineSpacing(LengthMetrics.vp(20))
TextArea({ text: 'This is the TextArea with lineSpacing set to 20_fp.' })
.fontSize(12)
.lineSpacing(LengthMetrics.fp(20))
TextArea({ text: 'This is the TextArea with lineSpacing set to 20_lpx.' })
.fontSize(12)
.lineSpacing(LengthMetrics.lpx(20))
TextArea({ text: 'This is the TextArea with lineSpacing set to 100%.' })
.fontSize(12)
.lineSpacing(LengthMetrics.percent(1))
TextArea({ text: 'The line spacing of this TextArea is set to 20_px, and the spacing is effective only between the lines.' })
.fontSize(12)
.lineSpacing(LengthMetrics.px(20), { onlyBetweenLines: true })
}.height(600).width(350).padding({ left: 35, right: 35, top: 35 })
}
}

Example 11: Setting Autofill
This example illustrates how to implement the autofill feature for text input using the contentType and enableAutoFill attributes, available since API version 12.
// xxx.ets
@Entry
@Component
struct TextAreaExample {
@State text: string = '';
build() {
Column() {
// Email address autofill.
TextArea({ placeholder: 'input your email...' })
.width('95%')
.height(40)
.margin(20)
.contentType(ContentType.EMAIL_ADDRESS)
.enableAutoFill(true)
.maxLength(20)
// Full street address autofill.
TextArea({ placeholder: 'input your street address...' })
.width('95%')
.height(40)
.margin(20)
.contentType(ContentType.FULL_STREET_ADDRESS)
.enableAutoFill(true)
.maxLength(20)
}.width('100%').height('100%').backgroundColor('#F1F3F5')
}
}
Example 12: Setting Line Break Rules
This example demonstrates the effects of different line break rules using the lineBreakStrategy attribute, available since API version 12.
// xxx.ets
@Entry
@Component
struct TextAreaExample {
@State message1: string =
"They can be classified as built-in components–those directly provided by the ArkUI framework and custom components – those defined by developers" +
"The built-in components include buttons radio buttonsprogress indicators and text You can set the rendering effect of these components in method chaining mode," +
"page components are divided into independent UI units to implement independent creation development and reuse of different units on pages making pages more engineering-oriented.";
@State lineBreakStrategyIndex: number = 0;
@State lineBreakStrategy: LineBreakStrategy[] =
[LineBreakStrategy.GREEDY, LineBreakStrategy.HIGH_QUALITY, LineBreakStrategy.BALANCED];
@State lineBreakStrategyStr: string[] = ['GREEDY', 'HIGH_QUALITY', 'BALANCED'];
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start }) {
Text('lineBreakStrategy').fontSize(9).fontColor(0xCCCCCC)
TextArea({ text: this.message1 })
.fontSize(12)
.border({ width: 1 })
.padding(10)
.width('100%')
.lineBreakStrategy(this.lineBreakStrategy[this.lineBreakStrategyIndex])
Row() {
Button('Current lineBreakStrategy value: ' + this.lineBreakStrategyStr[this.lineBreakStrategyIndex]).onClick(() => {
this.lineBreakStrategyIndex++;
if (this.lineBreakStrategyIndex > (this.lineBreakStrategyStr.length - 1)) {
this.lineBreakStrategyIndex = 0;
}
})
}.padding({ top: 10 })
}.height(700).width(370).padding({ left: 35, right: 35, top: 35 })
}
}

Example 13: Setting Insert and Delete Callbacks
This example showcases the implementation of insert and delete operations using the onWillInsert, onDidInsert, onWillDelete, and onDidDelete APIs, available since API version 12.
// xxx.ets
@Entry
@Component
struct TextAreaExample {
@State insertValue: string = "";
@State deleteValue: string = "";
@State insertOffset: number = 0;
@State deleteOffset: number = 0;
@State deleteDirection: number = 0;
@State currentValue_1: string = "";
@State currentValue_2: string = "";
build() {
Row() {
Column() {
TextArea({ text: "Insert callbacks" })
.width(300)
.height(60)
.onWillInsert((info: InsertValue) => {
this.insertValue = info.insertValue;
return true;
})
.onDidInsert((info: InsertValue) => {
this.insertOffset = info.insertOffset;
})
.onWillChange((info: EditableTextChangeValue) => {
this.currentValue_1 = info.content
return true
})
Text("insertValue:" + this.insertValue + " insertOffset:" + this.insertOffset).height(30)
Text("currentValue_1:" + this.currentValue_1).height(30)
TextArea({ text: "Delete callbacks" })
.width(300)
.height(60)
.onWillDelete((info: DeleteValue) => {
this.deleteValue = info.deleteValue;
this.deleteDirection = info.direction;
return true;
})
.onDidDelete((info: DeleteValue) => {
this.deleteOffset = info.deleteOffset;
this.deleteDirection = info.direction;
})
.onWillChange((info: EditableTextChangeValue) => {
this.currentValue_2 = info.content
return true
})
Text("deleteValue:" + this.deleteValue + " deleteOffset:" + this.deleteOffset).height(30)
Text("deleteDirection:" + (this.deleteDirection == 0 ? "BACKWARD" : "FORWARD")).height(30)
Text("currentValue_2:" + this.currentValue_2).height(30)
}.width('100%')
}
.height('100%')
}
}
Example 14: Setting Custom Menu Extensions
This example implements custom menu extension items for text using the editMenuOptions API (available since API version 12), allowing configuration of text content, icons, and callbacks. Menu data can also be configured through the onPrepareMenu callback (available since API version 20).
// xxx.ets
@Entry
@Component
struct TextAreaExample {
@State text: string = 'TextArea editMenuOptions';
@State endIndex: number = 0;
onCreateMenu = (menuItems: Array<TextMenuItem>) => {
// Replace $r('app.media.startIcon') with the image resource file you use.
let item1: TextMenuItem = {
content: 'create1',
icon: $r('app.media.startIcon'),
id: TextMenuItemId.of('create1'),
};
let item2: TextMenuItem = {
content: 'create2',
id: TextMenuItemId.of('create2'),
icon: $r('app.media.startIcon'),
};
// TextMenuItemId.autoFill is supported since API version 23.
let targetIndex = menuItems.findIndex(item => item.id.equals(TextMenuItemId.autoFill));
if (targetIndex !== -1) {
menuItems.splice(targetIndex, 1); // Delete an element at the target index.
}
menuItems.push(item1);
menuItems.unshift(item2);
return menuItems;
}
onMenuItemClick = (menuItem: TextMenuItem, textRange: TextRange) => {
if (menuItem.id.equals(TextMenuItemId.of("create2"))) {
console.info("Intercept id: create2 start:" + textRange.start + "; end:" + textRange.end);
return true;
}
if (menuItem.id.equals(TextMenuItemId.of("prepare1"))) {
console.info("Intercept id: prepare1 start:" + textRange.start + "; end:" + textRange.end);
return true;
}
if (menuItem.id.equals(TextMenuItemId.COPY)) {
console.info("Intercept COPY start:" + textRange.start + "; end:" + textRange.end);
return true;
}
if (menuItem.id.equals(TextMenuItemId.SELECT_ALL)) {
console.info("Do not intercept SELECT_ALL start:" + textRange.start + "; end:" + textRange.end);
return false;
}
return false;
}
onPrepareMenu = (menuItems: Array<TextMenuItem>) => {
// Replace $r('app.media.startIcon') with the image resource file you use.
let item1: TextMenuItem = {
content: 'prepare1_' + this.endIndex,
icon: $r('app.media.startIcon'),
id: TextMenuItemId.of('prepare1'),
};
menuItems.unshift(item1);
return menuItems;
}
@State editMenuOptions: EditMenuOptions = {
onCreateMenu: this.onCreateMenu,
onMenuItemClick: this.onMenuItemClick,
onPrepareMenu: this.onPrepareMenu
};
build() {
Column() {
TextArea({ text: this.text })
.width('95%')
.height(56)
.editMenuOptions(this.editMenuOptions)
.margin({ top: 100 })
.onTextSelectionChange((selectionStart: number, selectionEnd: number) => {
this.endIndex = selectionEnd;
})
}
.width("90%")
.margin("5%")
}
}

Example 15: Setting Text Overflow
This example demonstrates text ellipsis for overflow content and ellipsis position adjustment using the textOverflow, ellipsisMode, and maxLines attributes. The MULTILINE_START and MULTILINE_CENTER types are used to implement ellipsis at the start and middle positions for both single-line and multi-line text scenarios.
The maxLines attribute can be used to set the maximum number of lines to display, available since API version 10.
The textOverflow attribute can be used to set the display mode for overflow text, available since API version 12.
The ellipsisMode attribute can be used to set the ellipsis position, available since API version 18.
The MULTILINE_START and MULTILINE_CENTER enums are added to EllipsisMode since API version 24.
// xxx.ets
@Entry
@Component
struct EllipsisModeExample {
@State textIndex: number = 0;
@State text: string = "As the sun begins to set, casting a warm golden hue across the sky," +
"the world seems to slow down and breathe a sigh of relief. The sky is painted with hues of orange, " +
" pink, and lavender, creating a breath taking tapestry that stretches as far as the eye can see." +
"The air is filled with the sweet scent of blooming flowers, mingling with the earthy aroma of freshly turned soil.";
@State ellipsisModeIndex: number = 0;
@State ellipsisMode: (EllipsisMode | undefined | null)[] =
[EllipsisMode.START, EllipsisMode.END, EllipsisMode.CENTER, EllipsisMode.MULTILINE_START,
EllipsisMode.MULTILINE_CENTER, undefined, null]; // MULTILINE_START and MULTILINE_CENTER are added since API version 24.
@State ellipsisModeStr: string[] =
['START ', 'END', 'CENTER', 'MULTILINE_START', 'MULTILINE_CENTER', 'undefined', 'null'];
@State textOverflowIndex: number = 0;
@State textOverflow: TextOverflow[] = [TextOverflow.Ellipsis, TextOverflow.Clip];
@State textOverflowStr: string[] = ['Ellipsis', 'Clip'];
@State maxLinesIndex: number = 0;
@State maxLines: number[] = [1, 2, 3];
@State maxLinesStr: string[] = ['1', '2', '3'];
@State styleAreaIndex: number = 0;
@State styleArea: TextContentStyle[] = [TextContentStyle.INLINE, TextContentStyle.DEFAULT];
@State styleAreaStr: string[] = ['INLINE', 'DEFAULT'];
build() {
Column({ space: 20 }) {
TextArea({ text: this.text })
.textOverflow(this.textOverflow[this.textOverflowIndex])
.ellipsisMode(this.ellipsisMode[this.ellipsisModeIndex])
.maxLines(this.maxLines[this.maxLinesIndex])
.style(this.styleArea[this.styleAreaIndex])
.fontSize(30)
.margin(30)
Button('ellipsisMode Value: ' + this.ellipsisModeStr[this.ellipsisModeIndex]).onClick(() => {
this.ellipsisModeIndex++;
if (this.ellipsisModeIndex > (this.ellipsisModeStr.length - 1)) {
this.ellipsisModeIndex = 0;
}
}).fontSize(20)
Button('textOverflow Value: ' + this.textOverflowStr[this.textOverflowIndex]).onClick(() => {
this.textOverflowIndex++;
if (this.textOverflowIndex > (this.textOverflowStr.length - 1)) {
this.textOverflowIndex = 0;
}
}).fontSize(20)
Button('maxLines Value: ' + this.maxLinesStr[this.maxLinesIndex]).onClick(() => {
this.maxLinesIndex++;
if (this.maxLinesIndex > (this.maxLinesStr.length - 1)) {
this.maxLinesIndex = 0;
}
}).fontSize(20)
Button('Style Value: ' + this.styleAreaStr[this.styleAreaIndex]).onClick(() => {
this.styleAreaIndex++;
if (this.styleAreaIndex > (this.styleAreaStr.length - 1)) {
this.styleAreaIndex = 0;
}
}).fontSize(20)
}.height(600).width('100%')
}
}

Example 16: Implementing Custom Copy, Cut, and Paste Behavior
This example demonstrates how to listen for text selection menu actions using onCopy, onCut, and onPaste APIs. It shows how to intercept system paste functionality and implement custom paste behavior. In addition, the example uses maxFontScale and minFontScale attributes to configure font scaling limits.
// xxx.ets
@Entry
@Component
struct TextAreaExample {
@State text: string = '';
controller: TextAreaController = new TextAreaController();
build() {
Column() {
TextArea({
text: this.text,
placeholder: 'placeholder',
controller: this.controller
})
.placeholderColor(Color.Red)
.textAlign(TextAlign.Center)
.caretColor(Color.Green)
.caretStyle({ width: '2vp' })
.fontStyle(FontStyle.Italic)
.fontWeight(FontWeight.Bold)
.fontFamily('HarmonyOS Sans')
.inputFilter('[a-zA-Z]+', (value) => { // Only alphabetic input is allowed.
console.error(`unsupported char ${value}`);
})
.copyOption(CopyOptions.LocalDevice)
.enableKeyboardOnFocus(false)
.selectionMenuHidden(false)
.barState(BarState.On)
.type(TextAreaType.NORMAL)
.selectedBackgroundColor(Color.Orange)
.textIndent(2)
.halfLeading(true)
.minFontScale(1)
.maxFontScale(2)
.enablePreviewText(true)
.enableHapticFeedback(true)
.stopBackPress(false)// Delegate back press to other components.
.width(336)
.height(56)
.margin(20)
.fontSize(16)
.onEditChange((isEditing: boolean) => {
console.info(`isEditing ${isEditing}`);
})
.onCopy((value) => {
console.info(`copy ${value}`);
})
.onCut((value) => {
console.info(`cut ${value}`);
})
.onPaste((value, event) => {
// Prevent the default system paste behavior and implement custom logic.
if (event.preventDefault) {
event.preventDefault();
}
console.info(`paste:${value}`);
this.text = value;
})
.onTextSelectionChange((start: number, end: number) => {
console.info(`onTextSelectionChange start ${start}, end ${end}`);
})
.onContentScroll((totalOffsetX: number, totalOffsetY: number) => {
console.info(`onContentScroll offsetX ${totalOffsetX}, offsetY ${totalOffsetY}`);
})
}.width('100%').height('100%').backgroundColor('#F1F3F5')
}
}
Example 17: Setting the Minimum and Maximum Font Scale Factors
This example demonstrates how to set the minimum and maximum font scale factors using minFontScale and maxFontScale, available since API version 18. (This example uses system APIs. The application type needs to be set to a system application. For details, see the Available APIs of HarmonyAppProvision.)
// Enable application font scaling to follow system settings.
// Create a new directory named profile in the following path: AppScope/resources/base.
// Inside the newly created profile directory, create a file named configuration.json.
// Add the following code to the configuration.json file:
{
"configuration": {
"fontSizeScale": "followSystem",
"fontSizeMaxScale": "3.2"
}
}
// Modify the app.json5 file in AppScope as follows:
{
"app": {
"bundleName": "com.example.myapplication",
"vendor": "example",
"versionCode": 1000000,
"versionName": "1.0.0",
"icon": "$media:app_icon",
"label": "$string:app_name",
"configuration": "$profile:configuration"
}
}
// xxx.ets
import { abilityManager, Configuration } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
@Entry
@Component
struct TextAreaExample {
@State currentFontSizeScale: number = 1;
@State minFontScale: number = 0.85;
@State maxFontScale: number = 2;
// Set the font size.
async setFontScale(scale: number): Promise<void> {
let configInit: Configuration = {
language: 'zh-Ch',
fontSizeScale: scale,
};
// Update system font scaling.
// Add the ohos.permission.UPDATE_CONFIGURATION permission to the requestPermissions field in the module.json5 file of the project.
abilityManager.updateConfiguration(configInit, (err: BusinessError) => {
if (err) {
console.error(`updateConfiguration fail, err: ${JSON.stringify(err)}`);
} else {
this.currentFontSizeScale = scale;
console.info('updateConfiguration success.');
}
});
}
build() {
Column() {
Column({ space: 30 }) {
Text("Configure the minimum and maximum font scale factors using minFontScale and maxFontScale.")
TextArea({
placeholder: 'The text area can hold an unlimited amount of text. input your word...',
text: 'Use minFontScale and maxFontScale to adjust the maximum and minimum font scale factors for text display.'
})
.minFontScale(this.minFontScale)// Set the minimum font scale factor. If the parameter is set to undefined, the default scale factor is used.
.maxFontScale(this.maxFontScale) // Set the maximum font scale factor. If the parameter is set to undefined, the default scale factor is used.
}.width('100%')
Column() {
Row() {
Button('1x').onClick(() => {
this.setFontScale(1)
}).margin(10)
Button('1.75x').onClick(() => {
this.setFontScale(1.75)
}).margin(10)
}
Row() {
Button('2x').onClick(() => {
this.setFontScale(2)
}).margin(10)
Button('3.2x').onClick(() => {
this.setFontScale(3.2)
}).margin(10)
}
}.margin({ top: 50 })
}
}
}
| System font scale factor: 2x | System font scale factor: 3.2x |
|---|---|
![]() |
![]() |
Example 18: Setting Text Selection for a Specified Region
This example demonstrates how to set text selection for a specified region and the display/hide strategy of the menu using the setTextSelection API, available since API version 10.
// xxx.ets
@Entry
@Component
struct TextAreaExample {
controller: TextAreaController = new TextAreaController();
@State startIndex: number = 0;
@State endIndex: number = 0;
build() {
Column({ space: 3 }) {
Text('Selection start:' + this.startIndex + ' end:' + this.endIndex)
TextArea({ text: 'Hello World', controller: this.controller })
.width('95%')
.height(80)
.margin(10)
.defaultFocus(true)
.enableKeyboardOnFocus(true)
.onTextSelectionChange((selectionStart: number, selectionEnd: number) => {
this.startIndex = selectionStart;
this.endIndex = selectionEnd;
})
Button('setTextSelection [0,3], set menuPolicy is MenuPolicy.SHOW')
.onClick(() => {
this.controller.setTextSelection(0, 3, { menuPolicy: MenuPolicy.SHOW });
})
}
.width('100%')
.height('100%')
}
}

Example 19: Setting Text Stroke
This example demonstrates how to set the stroke width and color for text using the strokeWidth and strokeColor attributes, available since API version 20.
// xxx.ets
import { LengthMetrics } from '@kit.ArkUI';
@Entry
@Component
struct TextAreaExample {
build() {
Row() {
Column() {
Text('stroke feature').fontSize(9).fontColor(0xCCCCCC)
TextArea({ text: 'Text without stroke' })
.width('100%')
.height(60)
.borderWidth(1)
.fontSize(40)
TextArea({ text: 'Text with stroke' })
.width('100%')
.height(60)
.borderWidth(1)
.fontSize(40)
.strokeWidth(LengthMetrics.px(-3.0))
.strokeColor(Color.Red)
TextArea({ text: 'Text with stroke' })
.width('100%')
.height(60)
.borderWidth(1)
.fontSize(40)
.strokeWidth(LengthMetrics.px(3.0))
.strokeColor(Color.Red)
}.height('90%')
}
.width('90%')
.margin(10)
}
}

Example 20: Configuring Automatic Spacing Between Chinese and Western Text
This example shows how to configure automatic spacing between Chinese and Western characters using the enableAutoSpacing attribute, available since API version 20.
// xxx.ets
@Entry
@Component
struct TextAreaExample {
build() {
Row() {
Column() {
Text('Automatic spacing: Enabled').margin(5)
TextArea({text: '中文 Text'})
.enableAutoSpacing(true)
Text('Automatic spacing: Disabled').margin(5)
TextArea({text: '中文Text'})
.enableAutoSpacing(false)
}.height('100%')
}
.width('60%')
}
}

Example 21: Setting the Maximum Number of Lines
This example shows how to set the maximum number of lines using the maxLines attribute, available since API version 20. The text becomes scrollable when the maximum number of lines is exceeded.
// xxx.ets
@Entry
@Component
struct TextAreaExample {
build() {
Row() {
Column() {
TextArea({ text: '1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20' })
.fontSize(50)
.width('50%')
.borderWidth(1)
.margin(100)
.textOverflow(TextOverflow.Clip)
.maxLines(3, { overflowMode: MaxLinesMode.SCROLL })
}.height('90%')
}
.width('90%')
.margin(10)
}
}

Example 22: Setting the Minimum Number of Lines
This example shows how to set the minimum number of lines using the minLines attribute, available since API version 20.
// xxx.ets
@Entry
@Component
struct Index {
@State message: string = 'Hello World';
build() {
Row() {
Column() {
TextArea({ text: this.message })
.width('95%')
.fontSize(20)
.margin(10)
.minLines(3)
}
}
.width('90%')
.margin(10)
}
}

Example 23 Setting the Normal and Overflow Colors of the Character Counter
This example demonstrates how to set the normal and overflow colors of the character counter using the counterTextColor and counterTextOverflowColor parameters (available since API version 22) of the showCounter attribute.
import { ColorMetrics } from '@kit.ArkUI';
// xxx.ets
@Entry
@Component
struct TextAreaExample {
@State text: string = '';
controller: TextAreaController = new TextAreaController();
build() {
Column() {
TextArea({
text: this.text,
placeholder: 'The text area can hold an unlimited amount of text. input your word...',
controller: this.controller
})
.placeholderFont({ size: 16, weight: 400 })
.width(336)
.height(56)
.margin(20)
.fontSize(16)
.fontColor('#182431')
.backgroundColor('#FFFFFF')
.maxLength(4)
.showCounter(true, {
thresholdPercentage: 50,
highlightBorder: true,
counterTextColor: ColorMetrics.resourceColor(Color.Red),
counterTextOverflowColor: ColorMetrics.resourceColor(Color.Orange)
})
}.width('100%').height('100%').backgroundColor('#F1F3F5')
}
}

Example 24 Setting the Scrollbar Color
This example demonstrates how to set the color of the scrollbar using the scrollBarColor attribute, available since API version 22.
// xxx.ets
import { ColorMetrics } from '@kit.ArkUI';
@Entry
@Component
struct Index {
controller: TextAreaController = new TextAreaController();
build() {
Column() {
TextArea({
text: "Hello World TextArea\nHello World TextArea\nHello World TextArea\nHello World TextArea",
placeholder: 'Type to text area...',
controller: this.controller
})
.width(336)
.height(56)
.margin({bottom:5})
.fontSize(16)
.fontColor('#182431')
.backgroundColor('#FFFFFF')
.barState(BarState.On)
.scrollBarColor(undefined)
TextArea({
text: "Hello World TextArea\nHello World TextArea\nHello World TextArea\nHello World TextArea",
placeholder: 'Type to text area...',
controller: this.controller
})
.width(336)
.height(56)
.margin({bottom:5})
.fontSize(16)
.fontColor('#182431')
.backgroundColor('#FFFFFF')
.barState(BarState.On)
.scrollBarColor(ColorMetrics.resourceColor(Color.Orange))
TextArea({
text: "Hello World TextArea\nHello World TextArea\nHello World TextArea\nHello World TextArea",
placeholder: 'Type to text area...',
controller: this.controller
})
.width(336)
.height(56)
.margin({bottom:5})
.fontSize(16)
.fontColor('#182431')
.backgroundColor('#FFFFFF')
.barState(BarState.On)
.scrollBarColor(ColorMetrics.rgba(255, 100, 255))
}
.backgroundColor(Color.Blue).width('100%').height('100%')
}
}

Example 25: Setting the Placeholder Rich Text Style
This example demonstrates how to set the placeholder rich text style using the setStyledPlaceholder API, available since API version 22.
// xxx.ets
import { LengthMetrics } from '@kit.ArkUI';
@Entry
@Component
struct TextAreaExample {
styledString: MutableStyledString =
new MutableStyledString("段落标题\n正文第一段\n正文第二段indent 40 vp\n正文第三段textAlign居中对齐",
[
{
start: 0,
length: 4,
styledKey: StyledStringKey.FONT,
styledValue: new TextStyle({ fontSize: LengthMetrics.vp(24), fontWeight: FontWeight.Bolder })
},
{
start: 5,
length: 5,
styledKey: StyledStringKey.FONT,
styledValue: new TextStyle({ fontColor: Color.Gray })
},
{
start: 11,
length: 1,
styledKey: StyledStringKey.PARAGRAPH_STYLE,
styledValue: new ParagraphStyle({
textIndent: LengthMetrics.vp(40),
maxLines: 1,
overflow: TextOverflow.Ellipsis
})
},
{
start: 29,
length: 1,
styledKey: StyledStringKey.PARAGRAPH_STYLE,
styledValue: new ParagraphStyle({
textAlign: TextAlign.Center
})
}
]);
controller: TextAreaController = new TextAreaController();
aboutToAppear() {
this.controller.setStyledPlaceholder(this.styledString)
}
build() {
Scroll() {
Column() {
Text("TextArea placeholder富文本")
.fontSize(8)
TextArea({ controller: this.controller })
.width(200)
.fontSize(24)
.margin(10)
}
.width('100%')
}
}
}

Example 26 Setting Input Method Extension Information
This example demonstrates how to set input method extension information using the setExtraConfig method of IMEClient, available since API version 22.
// xxx.ets
@Entry
@Component
struct TextAreaExample {
build() {
Column() {
TextArea({ text: 'Execute the onWillAttachIME callback before starting the input method.'})
.onWillAttachIME((client: IMEClient) => {
client.setExtraConfig({
customSettings: {
name: "TextArea", // Custom property
id: client.nodeId // Custom property
}
})
})
}.height('100%')
}
}
Example 27: Setting Leading Punctuation Compression
This example demonstrates how to set leading punctuation compression using the compressLeadingPunctuation API. If a punctuation mark with a leading space appears at the start of a line, the punctuation mark will be compressed to the left boundary.
The compressLeadingPunctuation API is supported since API version 23.
// xxx.ets
@Entry
@Component
struct Index {
build() {
Column(){
TextArea({ text: "\u300CLeading punctuation compression enabled" })
.compressLeadingPunctuation(true)
.margin(5)
.fontSize(30)
.width("90%")
TextArea({ text: "\u300CLeading punctuation compression disabled" })
.compressLeadingPunctuation(false)
.fontSize(30)
.width("90%")
}
}
}

Example 28: Setting Adaptative Spacing
This example uses the includeFontPadding API to add the spacing of the first and last lines and the fallbackLineSpacing API to set adaptive line spacing.
The includeFontPadding and fallbackLineSpacing APIs are supported since API version 23.
// xxx.ets
const UYGHUR_TEXT: string = 'ياخشىمۇسەنياخشىمۇسەنياخشىمۇسەنياخشىمۇسەنياخشىمۇسەنياخشىمۇسەنياخشىمۇسەن';
@Entry
@Component
struct Index {
@State include: boolean | null | undefined = false;
@State fallback: boolean | null | undefined = false;
@State displayText: string = UYGHUR_TEXT;
build() {
Column() {
TextArea({
text: this.displayText,
placeholder:'Enter'
})
.includeFontPadding(this.include)
.fallbackLineSpacing(this.fallback)
.lineHeight(5)
.width('100%')
.height(100)
.backgroundColor('#eee')
.borderWidth(1)
.borderColor('#dddddd')
Scroll() {
Column() {
// --- Buttons related to IncludeFontPadding ---
Button('Set includePadding: ' + this.include)
.onClick(() => {
this.include = this.include === false ? true : false;
})
.margin({ bottom: 10 })
// --- Button related to FallbackLineSpacing ---
Button('Set fallbackLineSpacing: ' + this.fallback)
.onClick(() => {
this.fallback = this.fallback === false ? true : false;
})
.margin({ bottom: 10 })
}
.width('100%')
.padding(5)
}
.height(250)
.backgroundColor('transparent')
.scrollBarWidth(2)
.scrollBarColor('#888')
}
.width('100%')
.height('100%')
.padding(20)
}
}

Example 29: Setting the Drag Preview Style for Text Being Dragged
This example demonstrates how to set the drag preview style for text being dragged using the selectedDragPreviewStyle API.
The selectedDragPreviewStyle API is supported since API version 23.
@Entry
@Component
struct TextAreaTest {
build() {
Column() {
TextArea({ text: 'HelloWorld', placeholder: 'please input words' })
.copyOption(CopyOptions.InApp)
.width(200)
.height(50)
.margin(150)
.draggable(true)
.selectedDragPreviewStyle({color: 'rgba(227, 248, 249, 1)'})
}
.height('100%')
}
}

Example 30: Deleting the Last Character in a Text Box
This example demonstrates how to delete the last character in a text box using the deleteBackward API.
The deleteBackward API is added since API version 23.
@Entry
@Component
struct Page {
controller: TextAreaController = new TextAreaController();
build() {
Column() {
TextArea({ text: 'Deletebackward example', controller: this.controller})
Button('Delete backward')
.onClick(() => {
this.controller.deleteBackward();
})
}
}
}

Example 31: Setting the Text Layout Direction
This example demonstrates how to set the text layout direction using the textDirection API.
The textDirection API is supported since API version 23.
// xxx.ets
@Entry
@Component
struct TextAreaExample {
@State text: string = 'TextArea text direction example';
build() {
Column() {
Text('TextArea text direction: RTL, component layout direction: default')
.fontSize(12).width('90%')
TextArea({ text: this.text })
.width(336)
.height(56)
.margin(10)
.fontSize(16)
.textDirection(TextDirection.RTL)
.showCounter(true)
.maxLength(50)
Text('TextArea text direction: RTL, component layout direction: default, horizontal alignment: LEFT')
.fontSize(12).width('90%')
TextArea({ text: this.text })
.width(336)
.height(56)
.margin(10)
.fontSize(16)
.textDirection(TextDirection.RTL)
.textAlign(TextAlign.LEFT)
.showCounter(true)
.maxLength(50)
Text('TextArea text direction: LTR, component layout direction: Rtl')
.fontSize(12).width('90%')
TextArea({ text: this.text })
.width(336)
.height(56)
.margin(10)
.fontSize(16)
.textDirection(TextDirection.LTR)
.direction(Direction.Rtl)
.maxLength(50)
.showCounter(true)
}.width('100%').height('100%')
}
}
Example 32: Scrolling the Text in a Specified Range to the Visible Area
This example demonstrates how to scroll the text in a specified range to the visible area using the scrollToVisible API.
The scrollToVisible API is added since API version 23.
// xxx.ets
@Entry
@Component
struct TextAreaExample {
@State text: string = '123456789134567891234567891234567😁😁😁😁89123456789123456789123456789123456789123456789123';
controller: TextAreaController = new TextAreaController();
build() {
Column() {
TextArea({ text: this.text, controller: this.controller })
.width(336)
.height(150)
Button("Scroll Text to Visible Area").onClick(()=> {
this.controller.scrollToVisible({ start: 110, end: 115 })
})
}.width('100%').height('100%').backgroundColor('#F1F3F5')
}
aboutToAppear(): void {
for (let i = 0; i < 5; i++) {
this.text += this.text
}
}
}


