1# TextInput 2 3The **\<TextInput>** component provides single-line text input. 4 5> **NOTE** 6> 7> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. 8 9 10## Child Components 11 12Not supported 13 14 15## APIs 16 17TextInput(value?:{placeholder?: ResourceStr, text?: ResourceStr, controller?: TextInputController}) 18 19**Parameters** 20 21| Name | Type | Mandatory | Description | 22| ----------------------- | ---------------------------------------- | ---- | --------------- | 23| placeholder | [ResourceStr](ts-types.md#resourcestr) | No | Text displayed when there is no input. | 24| text | [ResourceStr](ts-types.md#resourcestr) | No | Current text input.<br>If the component has [stateStyles](ts-universal-attributes-polymorphic-style.md) or any other attribute that may trigger updating configured, you are advised to bind the state variable to the text in real time through the **onChange** event,<br>so as to prevent display errors when the component is updated.<br>Since API version 10, this parameter supports two-way binding through [$$](../../quick-start/arkts-two-way-sync.md).| 25| controller<sup>8+</sup> | [TextInputController](#textinputcontroller8) | No | Text input controller.| 26 27## Attributes 28 29Among the [universal attributes](ts-universal-attributes-size.md) and [universal text attributes](ts-universal-attributes-text-style.md), **fontColor**, **fontSize**, **fontStyle**, **fontWeight**, and **fontFamily** are supported. In addition, the following attributes are supported. 30 31| Name | Type | Description | 32| ------------------------ | ---------------------------------------- | ---------------------------------------- | 33| type | [InputType](#inputtype) | Text box type.<br>Default value: **InputType.Normal** | 34| placeholderColor | [ResourceColor](ts-types.md#resourcecolor) | Placeholder text color.<br>The default value follows the theme. | 35| placeholderFont | [Font](ts-types.md#font) | Placeholder text font.| 36| enterKeyType | [EnterKeyType](#enterkeytype) | Type of the Enter key.<br>Default value: **EnterKeyType.Done**| 37| caretColor | [ResourceColor](ts-types.md#resourcecolor) | Color of the caret in the text box.<br>Default value: **'#007DFF'** | 38| maxLength | number | Maximum number of characters in the text input. | 39| inputFilter<sup>8+</sup> | {<br>value: [ResourceStr](ts-types.md#resourcestr),<br>error?: (value: string) => void<br>} | Regular expression for input filtering. Only inputs that comply with the regular expression can be displayed. Other inputs are filtered out. The regular expression can match single characters, but not strings.<br>- **value**: regular expression to set.<br>- **error**: filtered-out content to return when regular expression matching fails.| 40| copyOption<sup>9+</sup> | [CopyOptions](ts-appendix-enums.md#copyoptions9) | Whether copy and paste is allowed.<br>Default value: **CopyOptions.LocalDevice**<br>If this attribute is set to **CopyOptions.None**, the paste operation is allowed, but not the copy or cut operation.<br>**NOTE**<br>For dragging, **copyOption** only restricts whether text is selected and does not involve the dragging scope.| 41| showPasswordIcon<sup>9+</sup> | boolean | Whether to display the password icon at the end of the password text box.<br>Default value: **true**| 42| style<sup>9+</sup> | [TextInputStyle](#textinputstyle9) \| [TextContentStyle](ts-appendix-enums.md#textcontentstyle10) | Text input style. For the inline input style, only **InputType.Normal** is supported.<br>Default value: **TextInputStyle.Default**| 43| textAlign<sup>9+</sup> | [TextAlign](ts-appendix-enums.md#textalign) | Horizontal alignment of the text.<br>Default value: **TextAlign.Start**<br>**NOTE**<br>Available options are **TextAlign.Start**, **TextAlign.Center**, and **TextAlign.End**.<br>To set vertical alignment for the text, use the [align](ts-universal-attributes-location.md) attribute. The **align** attribute alone does not control the horizontal position of the text. In other words, **Alignment.TopStart**, **Alignment.Top**, and **Alignment.TopEnd** produce the same effect, top-aligning the text; **Alignment.Start**, **Alignment.Center**, and **Alignment.End** produce the same effect, centered-aligning the text vertically; **Alignment.BottomStart**, **Alignment.Bottom**, and **Alignment.BottomEnd** produce the same effect, bottom-aligning the text. | 44| selectedBackgroundColor<sup>10+</sup> | [ResourceColor](ts-types.md#resourcecolor) | Background color of the selected text.<br>If the opacity is not set, a 20% opacity will be used.| 45| caretStyle<sup>10+</sup> | {<br>width: [Length](ts-types.md#length)<br>} | Caret style. It cannot be set in percentage. | 46| caretPosition<sup>10+</sup> | number | Caret position.| 47| showUnit<sup>10+</sup> | [CustomBuilder](ts-types.md#custombuilder8) | Unit for content in the component.<br>By default, there is no unit.<br>This attribute must be used together with **showUnderline**. It is effective only when **showUnderline** is set to **true**.| 48| showError<sup>10+</sup> | string \| undefined | Error message displayed when an error occurs.<br>By default, no error message is displayed.<br>**NOTE**<br>If the parameter type is string and the input content does not comply with specifications, the error message is displayed. If the parameter type is undefined, no error message is displayed. See [Example 2](#example-2).| 49| showUnderline<sup>10+</sup> | boolean | Whether to show an underline. By default, the underline comes in the color of **'#33182431'**, thickness of 1 px, and text box size of 48 vp. The underline supports only the **InputType.Normal** type.<br>Default value: **false**| 50| passwordIcon<sup>10+</sup> | [PasswordIcon](#passwordicon10) | Password icon to display at the end of the password text box.<br>By default, the system-provided icon is used.| 51| enableKeyboardOnFocus<sup>10+</sup> | boolean | Whether to enable the input method when the component obtains focus in a way other than clicking.<br>Default value: **true** | 52| selectionMenuHidden<sup>10+</sup> | boolean | Whether to display the text selection menu when the text box is long-pressed or right-clicked.<br>Default value: **false**| 53| barState<sup>10+</sup> | [BarState](ts-appendix-enums.md#barstate) | Scrollbar state when the inline input style is used.<br>Default value: **BarState.Auto**| 54| maxLines<sup>10+</sup> | number | Maximum number of lines that can be displayed when the inline input style is used.<br>Default value: **3**<br>**NOTE**<br>Value range: (0, +∞)| 55| customKeyboard<sup>10+</sup> | [CustomBuilder](ts-types.md#custombuilder8) | Custom keyboard.<br>**NOTE**<br>When a custom keyboard is set, activating the text box opens the specified custom component, instead of the system input method, and the **enterKeyType** attribute setting for the system keyboard will not take effect.<br>The custom keyboard's height can be set through the **height** attribute of the custom component's root node, and its width is fixed at the default value.<br>The custom keyboard is displayed on top of the current page, without compressing or raising the page.<br>The custom keyboard cannot obtain the focus, but it blocks gesture events.<br>By default, the custom keyboard is closed when the input component loses the focus. You can also use the [TextInputController](#textinputcontroller8).[stopEditing](#stopediting10) API to close the keyboard.| 56> **NOTE** 57> 58> The default value of the universal attribute [padding](ts-universal-attributes-size.md) is as follows:<br>{<br> top: 8 vp,<br> right: 16 vp,<br> bottom: 8 vp,<br> left: 16 vp<br> } 59> 60> Since API version 10, **.width('auto')** can be set for the **\<TextInput>** 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 [Size](ts-universal-attributes-size.md#attributes). 61 62## EnterKeyType 63 64| Name | Description | 65| ------------------- | --------- | 66| Go | The Enter key is labeled "Go." | 67| Search | The Enter key is labeled "Search." | 68| Send | The Enter key is labeled "Send." | 69| Next | The Enter key is labeled "Next."| 70| Done | The Enter key is labeled "Done." | 71 72## InputType 73 74| Name | Description | 75| ------------------ | ------------- | 76| Normal | Normal input mode. In this mode, there is no special restriction on the input characters.| 77| Password | Password input mode. This mode accepts only digits, letters, underscores (_), spaces, and special characters. An eye icon is used to show or hide the password, and the password is hidden behind dots by default. The password input mode does not support underlines.| 78| Email | Email address input mode. This mode accepts only digits, letters, underscores (_), dots (.), and one at sign (@).| 79| Number | Digit input mode. | 80| PhoneNumber<sup>9+</sup> | Phone number input mode.<br>The value can contain digits, plus signs (+), hyphens (-), asterisks (*), and number signs (#). The length is not limited.| 81 82## TextInputStyle<sup>9+</sup> 83 84| Name | Description | 85| ------------------ | ------------- | 86| Default | Default style. The caret width is fixed at 1.5 vp, and the caret height is subject to the background height and font size of the selected text. | 87| Inline | Inline input style. The background height of the selected text is the same as the height of the text box.<br>This style is used in scenarios where editing and non-editing states are obvious, for example, renaming in the file list view.<br>The **showError** attribute is not supported for this style.| 88 89## PasswordIcon<sup>10+</sup> 90 91| Name | Type | Mandatory| Description | 92| ---------- | -------------------------------------------------- | ---- | -------------------------------------------------- | 93| onIconSrc | string \|[Resource](ts-types.md#resource)| No | Icon that can be used to hide the password in password input mode.| 94| offIconSrc | string \|[Resource](ts-types.md#resource)| No | Icon that can be used to show the password in password input mode.| 95 96## Events 97 98In addition to the [universal events](ts-universal-events-click.md), the following events are supported. 99 100| Name | Description | 101| ------------------------------------------------------------ | ------------------------------------------------------------ | 102| onChange(callback: (value: string) => void) | Triggered when the input in the text box changes.<br>**value**: text content.<br>This event is triggered when any of the following conditions is met:<br>1. Keyboard input is received.<br>2. Paste and cut is performed.<br>3. Ctrl+V is pressed.| 103| onSubmit(callback: (enterKey: EnterKeyType) => void) | Triggered when the Enter key on the keyboard is pressed. The return value is the current type of the Enter key.<br>**enterKeyType**: type of the Enter key. For details, see [EnterKeyType](#enterkeytype).| 104| onEditChanged(callback: (isEditing: boolean) => void)<sup>(deprecated)</sup> | Triggered when the input status changes. Since API version 8, **onEditChange** is recommended.| 105| onEditChange(callback: (isEditing: boolean) => void)<sup>8+</sup> | Triggered when the input status changes. The text box is in the editing state when the caret is placed in it. If the value of **isEditing** is **true**, text input is in progress.| 106| onCopy(callback:(value: string) => void)<sup>8+</sup> | Triggered when the copy button on the pasteboard, which displays when the text box is long pressed, is clicked.<br>**value**: text to be copied.| 107| onCut(callback:(value: string) => void)<sup>8+</sup> | Triggered when the cut button on the pasteboard, which displays when the text box is long pressed, is clicked.<br>**value**: text to be cut.| 108| onPaste(callback:(value: string) => void)<sup>8+</sup> | Triggered when the paste button on the pasteboard, which displays when the text box is long pressed, is clicked.<br>**value**: text to be pasted.| 109| onTextSelectionChange(callback: (selectionStart: number, selectionEnd: number) => void)<sup>10+</sup> | Triggered when the text selection position changes.<br>**selectionStart**: start position of the text selection area. The start position of text in the text box is **0**.<br>**selectionEnd**: end position of the text selection area.| 110| onContentScroll(callback: (totalOffsetX: number, totalOffsetY: number) => void)<sup>10+</sup> | Triggered when the text content is scrolled.<br>**totalOffsetX**: offset in the X coordinate of the text in the content area, in px.<br>**totalOffsetY**: offset in the Y coordinate of the text in the content area, in px.| 111 112## TextInputController<sup>8+</sup> 113 114Implements the controller of the **\<TextInput>** component. 115 116### Objects to Import 117``` 118controller: TextInputController = new TextInputController() 119``` 120### caretPosition<sup>8+</sup> 121 122caretPosition(value: number): void 123 124Sets the position of the caret. 125 126**Parameters** 127 128| Name| Type| Mandatory| Description | 129| ------ | -------- | ---- | -------------------------------------- | 130| value | number | Yes | Length from the start of the string to the position where the caret is located.| 131### setTextSelection<sup>10+</sup> 132 133setTextSelection(selectionStart: number, selectionEnd: number): void 134 135Sets the text selection area, which will be highlighted. 136 137**Parameters** 138 139| Name | Type| Mandatory| Description | 140| -------------- | -------- | ---- | ---------------------- | 141| selectionStart | number | Yes | Start position of the text selection range. The start position of text in the text box is 0.| 142| selectionEnd | number | Yes | End position of the text selection range.| 143> **NOTE** 144> 145> If **selectionStart** or **selectionEnd** is set to **undefined**, the value **0** will be used. 146### stopEditing<sup>10+</sup> 147 148stopEditing(): void 149 150Exits the editing state. 151 152### getTextContentRect<sup>10+</sup> 153 154getTextContentRect(): [RectResult](#rectresult10) 155 156Obtains the position of the edited text area relative to the component and its size. The unit of the return value is pixel. 157 158**Return value** 159 160| Type | Description | 161| ------------------- | -------- | 162| [RectResult](#rectresult10) | Position of the edited text area relative to the component and its size.| 163 164> **NOTE** 165> 166> - If no text is entered, the return value contains the position information, but the size is 0. 167> - The position information is the offset of the first character relative to the editable area. 168 169### RectResult<sup>10+</sup> 170 171Sets the position and size, in pixels. 172 173| Parameter | Type | Description| 174| ------- | ------ | ----------------------- | 175| x | number | X coordinate.| 176| y | number | Y coordinate.| 177| width | number | Content width.| 178| height | number | Content height.| 179 180 181### getTextContentLineCount<sup>10+</sup> 182 183getTextContentLineCount(): number 184 185Obtains the number of lines of the edited text. 186 187**Return value** 188 189| Type | Description | 190| ----- | -------- | 191| number| Number of lines of the edited text.| 192 193## Example 194 195### Example 1 196 197```ts 198// xxx.ets 199@Entry 200@Component 201struct TextInputExample { 202 @State text: string = '' 203 controller: TextInputController = new TextInputController() 204 205 build() { 206 Column() { 207 TextInput({ text: this.text, placeholder: 'input your word...', controller: this.controller }) 208 .placeholderColor(Color.Grey) 209 .placeholderFont({ size: 14, weight: 400 }) 210 .caretColor(Color.Blue) 211 .width(400) 212 .height(40) 213 .margin(20) 214 .fontSize(14) 215 .fontColor(Color.Black) 216 .inputFilter('[a-z]', (e) => { 217 console.log(JSON.stringify(e)) 218 }) 219 .onChange((value: string) => { 220 this.text = value 221 }) 222 Text(this.text) 223 Button('Set caretPosition 1') 224 .margin(15) 225 .onClick(() => { 226 // Move the caret to after the first entered character. 227 this.controller.caretPosition(1) 228 }) 229 // Password text box. 230 TextInput({ placeholder: 'input your password...' }) 231 .width(400) 232 .height(40) 233 .margin(20) 234 .type(InputType.Password) 235 .maxLength(9) 236 .showPasswordIcon(true) 237 // Inline-style text box. 238 TextInput({ text: 'inline style' }) 239 .width(400) 240 .height(50) 241 .margin(20) 242 .borderRadius(0) 243 .style(TextInputStyle.Inline) 244 }.width('100%') 245 } 246} 247``` 248 249 250 251### Example 2 252 253```ts 254@Entry 255@Component 256struct TextInputExample { 257 @State PassWordSrc1: Resource = $r('app.media.onIcon') 258 @State PassWordSrc2: Resource = $r('app.media.offIcon') 259 @State TextError: string = '' 260 @State Text: string = '' 261 @State NameText: string = 'test' 262 263 @Builder itemEnd() { 264 Select([{ value: 'KB' }, 265 { value: 'MB' }, 266 { value: 'GB' }, 267 { value: 'TB', }]) 268 .height("48vp") 269 .borderRadius(0) 270 .selected(2) 271 .align(Alignment.Center) 272 .value('MB') 273 .font({ size: 20, weight: 500 }) 274 .fontColor('#182431') 275 .selectedOptionFont({ size: 20, weight: 400 }) 276 .optionFont({ size: 20, weight: 400 }) 277 .backgroundColor(Color.Transparent) 278 .responseRegion({ height: "40vp", width: "80%", x: '10%', y: '6vp' }) 279 .onSelect((index: number) => { 280 console.info('Select:' + index) 281 }) 282 } 283 284 build() { 285 Column({ space: 20 }) { 286 // Customize the password icon. 287 TextInput({ placeholder: 'Custom password icon' }) 288 .type(InputType.Password) 289 .width(380) 290 .height(60) 291 .passwordIcon({ onIconSrc: this.PassWordSrc1, offIconSrc: this.PassWordSrc2 }) 292 // Show an underline. 293 TextInput({ placeholder: 'Underline style' }) 294 .showUnderline(true) 295 .width(380) 296 .height(60) 297 .showError('Error') 298 .showUnit(this.itemEnd.bind(this)) 299 300 Text (`User name: ${this.Text}`) 301 .width('95%') 302 TextInput({ placeholder: 'Enter user name', text: this.Text }) 303 .showUnderline(true) 304 .width(380) 305 .showError(this.TextError) 306 .onChange((value: string) => { 307 this.Text = value 308 }) 309 .onSubmit(() => {// If the entered user name is incorrect, the text box will be cleared and the error message will be displayed. 310 if (this.Text == this.NameText) { 311 this.TextError = '' 312 } else { 313 this.TextError ='Incorrect user name.' 314 this.Text = '' 315 } 316 }) 317 318 }.width('100%') 319 } 320} 321``` 322 323 324 325### Example 3 326 327```ts 328// xxx.ets 329@Entry 330@Component 331struct TextInputExample { 332 controller: TextInputController = new TextInputController() 333 @State inputValue: string = "" 334 335 // Create a custom keyboard component. 336 @Builder CustomKeyboardBuilder() { 337 Column() { 338 Button('x').onClick(() => { 339 // Disable the custom keyboard. 340 this.controller.stopEditing() 341 }) 342 Grid() { 343 ForEach([1, 2, 3, 4, 5, 6, 7, 8, 9, '*', 0, '#'], (item:number|string) => { 344 GridItem() { 345 Button(item + "") 346 .width(110).onClick(() => { 347 this.inputValue += item 348 }) 349 } 350 }) 351 }.maxCount(3).columnsGap(10).rowsGap(10).padding(5) 352 }.backgroundColor(Color.Gray) 353 } 354 355 build() { 356 Column() { 357 TextInput({ controller: this.controller, text: this.inputValue }) 358 // Bind the custom keyboard. 359 .customKeyboard(this.CustomKeyboardBuilder()).margin(10).border({ width: 1 }) 360 } 361 } 362} 363``` 364 365 366