# Angular SmartTextarea Component

SmartTextarea suggests the end of the sentence being typed as ghost text, accepted with Tab and dismissed with Escape, from a role, a context and phrases you give. It works with every kind of Angular form, respects IME composition and announces its suggestions, with any model through a small adapter to your own backend.

## Basic

SmartTextarea is a textarea that suggests the end of the sentence being typed, shown as gray ghost text after the caret. Tab accepts it, Escape dismisses it, and typing goes on as usual: a suggestion that matches the typed letters stays. The suggestion is asked after a pause in the typing, set by delay , with the text around the caret. The demos of this page answer offline with fakeAIAssistAdapter ; type "Thank you for", "I will send" or "Let me know".

```typescript
import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { fakeAIAssistAdapter } from '@exhaustive-ui/core/aiassist';
import { SmartTextareaModule } from '@exhaustive-ui/core/smarttextarea';

@Component({
    template: `
        <div class="card flex flex-col gap-2">
            <label for="st-reply" class="font-medium">Reply</label>
            <p-smart-textarea inputId="st-reply" [(ngModel)]="reply" [adapter]="adapter" [rows]="5" fluid />
        </div>
    `,
    standalone: true,
    imports: [SmartTextareaModule, FormsModule]
})
export class SmarttextareaBasicDemo {
    reply = '';

    adapter = fakeAIAssistAdapter({
        latency: 150,
        respond: ({ text }) => {
            const endings: [RegExp, string][] = [
                [/thank you for\s*$/i, ' your quick answer.'],
                [/thank you\s*$/i, ' for your patience.'],
                [/i will send\s*$/i, ' you the report by Friday.'],
                [/let me know\s*$/i, ' if you have any questions.'],
                [/looking forward\s*$/i, ' to hearing from you.'],
                [/(^|[.!?]\s+)(hi|hello) \w+,?\s*$/i, ' I hope you are doing well.']
            ];
            return endings.find(([pattern]) => pattern.test(text))?.[1] ?? '';
        }
    });
}
```

## Adapter and Streaming

SmartTextarea sends no request of its own: an adapter connects it to the model of your choice, through an endpoint of your application that holds the API key. Never put the key in the browser. The request has the completion task, the text before the caret, instructions built from role , context and phrases , and a context with them, the text after the caret and maxWords . The answer is the words that come next, as a string, a promise or a stream of chunks, shown as they arrive. A request is cancelled with its AbortSignal as soon as the user types, moves the caret or leaves the field, so a fast and small model fits this task best. Give the adapter with adapter , or to all the components with provideAIAssist ; the same endpoint serves InlineAIAssist and SmartPasteButton.

## Customization

role tells the model who writes, context gives it the facts it may use, such as opening hours or an order number, and phrases lists sentences to suggest as they are: a phrase whose beginning matches the typed text is suggested at once, without calling the adapter. acceptKey sets the key that accepts, Tab , ArrowRight or Enter , maxWords limits the length of a suggestion, minTextLength the text to type first, and showKeyHint shows the key after the suggestion.

```typescript
import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { fakeAIAssistAdapter } from '@exhaustive-ui/core/aiassist';
import { SmartTextareaModule } from '@exhaustive-ui/core/smarttextarea';

@Component({
    template: `
        <div class="card flex flex-col gap-2">
            <label for="st-support" class="font-medium">Answer to the customer</label>
            <p-smart-textarea
                inputId="st-support"
                [(ngModel)]="answer"
                [adapter]="adapter"
                role="A support agent of an online bike shop, answering a customer"
                context="The shop is open Monday to Saturday, 9am to 7pm. Order 4521 shipped on December 1 with tracking number FR-88213."
                [phrases]="phrases"
                acceptKey="ArrowRight"
                [maxWords]="16"
                [rows]="5"
                fluid
            />
        </div>
    `,
    standalone: true,
    imports: [SmartTextareaModule, FormsModule]
})
export class SmarttextareaCustomizationDemo {
    answer = '';

    phrases = ['Thank you for contacting us.', 'Your order shipped on December 1 with tracking number FR-88213.', 'We are open Monday to Saturday, from 9am to 7pm.', 'Kind regards, the support team'];

    adapter = fakeAIAssistAdapter({
        latency: 150,
        respond: ({ text }) => (/your order\s*$/i.test(text) ? ' shipped on December 1, it should arrive within three days.' : /(^|\s)we\s*$/i.test(text) ? ' are sorry for the delay.' : '')
    });
}
```

## Reactive Forms

SmartTextarea can also be used with reactive forms, bound with formControlName . An accepted suggestion updates the value of the control like typed text.

```typescript
import { Component } from '@angular/core';
import { FormControl, FormGroup, ReactiveFormsModule, Validators } from '@angular/forms';
import { fakeAIAssistAdapter } from '@exhaustive-ui/core/aiassist';
import { MessageModule } from '@exhaustive-ui/core/message';
import { SmartTextareaModule } from '@exhaustive-ui/core/smarttextarea';

@Component({
    template: `
        <div class="card">
            <form [formGroup]="review" class="flex flex-col gap-2">
                <label for="st-review" class="font-medium">Review</label>
                <p-smart-textarea inputId="st-review" formControlName="text" [adapter]="adapter" [invalid]="review.controls.text.invalid && review.controls.text.touched" [rows]="4" fluid />
                @if (review.controls.text.invalid && review.controls.text.touched) {
                    <p-message severity="error" size="small" variant="simple">Write at least 20 characters.</p-message>
                }
            </form>
        </div>
    `,
    standalone: true,
    imports: [SmartTextareaModule, ReactiveFormsModule, MessageModule]
})
export class SmarttextareaReactiveformsDemo {
    review = new FormGroup({
        text: new FormControl('', [Validators.required, Validators.minLength(20)])
    });

    adapter = fakeAIAssistAdapter({
        latency: 150,
        respond: ({ text }) => (/the bike\s*$/i.test(text) ? ' arrived quickly and well packed.' : /i would\s*$/i.test(text) ? ' recommend this shop to my friends.' : '')
    });
}
```

## Signal Forms

With Angular Signal Forms , the [formField] directive binds the component to a field, which also sets its disabled, read-only and invalid states.

```typescript
import { Component, signal } from '@angular/core';
import { form, FormField, maxLength } from '@angular/forms/signals';
import { fakeAIAssistAdapter } from '@exhaustive-ui/core/aiassist';
import { SmartTextareaModule } from '@exhaustive-ui/core/smarttextarea';

@Component({
    template: `
        <div class="card flex flex-col gap-2">
            <label for="st-bio" class="font-medium">Bio</label>
            <p-smart-textarea inputId="st-bio" [formField]="profile.bio" [adapter]="adapter" role="A web developer writing the bio of a profile" [rows]="3" fluid />
            <small class="text-surface-600 dark:text-surface-300">{{ model().bio.length }} / 200</small>
        </div>
    `,
    standalone: true,
    imports: [SmartTextareaModule, FormField]
})
export class SmarttextareaSignalformsDemo {
    model = signal({ bio: '' });

    profile = form(this.model, (path) => {
        maxLength(path.bio, 200);
    });

    adapter = fakeAIAssistAdapter({
        latency: 150,
        respond: ({ text }) => (/i am\s*$/i.test(text) ? ' a web developer who loves accessible interfaces.' : /i work\s*$/i.test(text) ? ' with Angular and TypeScript every day.' : '')
    });
}
```

## Accessibility

Screen Reader SmartTextarea renders a native textarea , labelled with inputId and a label , ariaLabelledBy or ariaLabel . The textarea is described by a hidden hint, "Suggestions appear as you type. Press Tab to accept one, Escape to dismiss it.", added to ariaDescribedBy . The ghost text is hidden from assistive technologies: a polite live region announces each suggestion with its key, such as "Suggestion: your quick answer. Press Tab to accept.", and "Suggestion accepted" once accepted. announce turns these announcements off. While a suggestion is shown, the accept key accepts it instead of its usual action, so Tab moves the focus out of the field only when there is no suggestion; choose ArrowRight with acceptKey to keep Tab for the focus. No suggestion is asked during an IME composition, nor in a read-only or disabled field, and suggestions turns them off. The ghost text has a 4.5:1 contrast or more in both color schemes, and the texts are translated with labels , and the smartTextareaHint , aiSuggestion and aiSuggestionAccepted keys of the aria translation.

## Smart Textarea

SmartTextarea suggests the end of the sentence being typed as ghost text after the caret, from the text, a role, a context and phrases, through an adapter to the model of your choice. Tab accepts it, Escape dismisses it, and typing goes on. It works with template-driven forms, reactive forms and Signal Forms.

### Props

| Name | Type | Default | Description |
|------|------|---------|-------------|
| dt | Object | undefined | Defines scoped design tokens of the component. |
| unstyled | boolean | undefined | Indicates whether the component should be rendered without styles. |
| pt | SmartTextareaPassThrough | undefined | Used to pass attributes to DOM elements inside the component. |
| ptOptions | PassThroughOptions | undefined | Used to configure passthrough(pt) options of the component. |
| required | boolean | false | There must be a value (if set). |
| invalid | boolean | false | When present, it specifies that the component should have invalid state style. |
| touched | boolean | undefined | Whether the field has been touched. Signal Forms sets it through  `[formField]` : the invalid style and  `aria-invalid`  then wait until the field is touched, or the form is submitted, like the error messages. Left unset,  `invalid`  applies at once. |
| $invalid | Signal<boolean> | - | The invalid state shown by the component:  `invalid` , once the field is touched when  `touched`  is set; undefined when  `invalid`  is unset. |
| disabled | boolean | false | When present, it specifies that the component should have disabled state style. |
| name | string | undefined | When present, it specifies that the name of the input. |
| fluid | boolean | false | Spans 100% width of the container when enabled. |
| variant | "filled" \| "outlined" | 'outlined' | Specifies the input variant of the component. |
| size | "small" \| "large" | undefined | Specifies the size of the component. |
| inputSize | number | undefined | Specifies the visible width of the input element in characters. |
| pattern | string | undefined | Specifies the value must match the pattern. |
| min | number | undefined | The value must be greater than or equal to the value. |
| max | number | undefined | The value must be less than or equal to the value. |
| step | number | undefined | Unless the step is set to the any literal, the value must be min + an integral multiple of the step. |
| minlength | number | undefined | The number of characters (code points) must not be less than the value of the attribute, if non-empty. |
| maxlength | number | undefined | The number of characters (code points) must not exceed the value of the attribute. |
| adapter | AIAssistAdapter \| AIAssistCompleteFn | - | Adapter that asks the model for a suggestion, or its complete function. Defaults to the one given to provideAIAssist. |
| role | string | - | Who writes and why, sent to the model, such as "A support agent answering a customer about an order". |
| context | string | - | Facts the text may use, sent to the model, such as an order number or opening hours. |
| phrases | string[] | - | Phrases the user often writes. When the end of the text starts one of them, its rest is suggested at once, without the model; the model is also asked to reuse them. |
| delay | number | 500 | Delay in milliseconds between the last keystroke and the request. |
| minTextLength | number | 3 | Minimum length of the text before a suggestion is asked for. |
| maxWords | number | 12 | Maximum number of words of a suggestion. |
| contextLength | number | 1500 | Number of characters before the caret sent to the model. |
| acceptKey | SmartTextareaAcceptKey | 'Tab' | Key that accepts the suggestion: Tab, the right arrow at the end of the text, or Enter. Without a suggestion, the key keeps its usual behavior. |
| suggestions | boolean | true | Whether suggestions are asked for. The field stays a plain textarea when false. |
| announce | boolean | true | Whether the suggestions are announced to screen readers, politely, once complete. |
| showKeyHint | boolean | true | Whether the accept key is shown after the suggestion. |
| labels | Partial<SmartTextareaLabels> | - | Texts of the component, merged with the translation and the defaults. |
| autoResize | boolean | false | Whether the textarea grows with its content. |
| rows | number | - | Number of visible lines of the textarea. |
| cols | number | - | Visible width of the textarea in characters. |
| placeholder | string | - | Placeholder of the textarea. |
| readonly | boolean | false | Whether the text can be selected but not changed. No suggestion is shown. |
| inputId | string | - | Identifier of the textarea, to link a label to it. |
| inputStyle | { [klass: string]: any } | - | Inline style of the textarea. |
| inputStyleClass | string | - | Style class of the textarea. |
| tabindex | number | - | Index of the textarea in the tab order. |
| ariaLabel | string | - | Accessible name of the textarea, when there is no visible label. |
| ariaLabelledBy | string | - | Identifier of the element that labels the textarea. |
| ariaDescribedBy | string | - | Identifiers of the elements that describe the textarea, a hint for instance. The description of the keys is added after them. |

### Emits

| Name | Parameters | Description |
|------|------------|-------------|
| onSuggest | event: SmartTextareaSuggestEvent | Callback to invoke when a complete suggestion is shown. |
| onAccept | event: SmartTextareaAcceptEvent | Callback to invoke when a suggestion is accepted. |
| onDismiss | value: void | Callback to invoke when a suggestion is dismissed with Escape. |
| onError | event: SmartTextareaErrorEvent | Callback to invoke when the adapter fails. The field keeps working without suggestion. |
| onFocus | event: FocusEvent | Callback to invoke when the textarea receives focus. |
| onBlur | event: FocusEvent | Callback to invoke when the textarea loses focus. |

### Methods

| Name | Parameters | Return Type | Description |
|------|------------|-------------|-------------|
| accept | event: Event | void | Accepts the suggestion: inserts it at the caret, as typed text that Ctrl+Z or ⌘Z undoes. |
| dismiss |  | void | Removes the suggestion and cancels the request in progress. |
| suggest |  | void | Asks for a suggestion now, without waiting for the delay. Nothing happens when the caret is not at the end of a line. |
| focus |  | void | Moves the focus to the textarea. |

## Pass Through Options

| Name | Type | Description |
|------|------|-------------|
| host | PassThroughOption<HTMLElement, I> | Used to pass attributes to the host's DOM element. |
| root | PassThroughOption<HTMLElement, I> | Used to pass attributes to the root's DOM element. |
| pcTextarea | TextareaPassThrough | Used to pass attributes to the Textarea. |
| mirror | PassThroughOption<HTMLDivElement, I> | Used to pass attributes to the mirror element laid over the textarea, that shows the suggestion after the text. |
| suggestion | PassThroughOption<HTMLSpanElement, I> | Used to pass attributes to the suggestion, the ghost text. |
| key | PassThroughOption<HTMLElement, I> | Used to pass attributes to the accept key shown after the suggestion. |
| hint | PassThroughOption<HTMLSpanElement, I> | Used to pass attributes to the hidden description of the keys. |
| liveRegion | PassThroughOption<HTMLSpanElement, I> | Used to pass attributes to the live region that announces the suggestions. |

## Theming

### CSS Classes

| Class | Description |
|-------|-------------|
| p-smarttextarea | Class name of the root element |
| p-smarttextarea-suggesting | Class name of the root element while a suggestion is shown |
| p-smarttextarea-fluid | Class name of the root element when fluid |
| p-smarttextarea-input | Class name of the textarea element |
| p-smarttextarea-mirror | Class name of the mirror element laid over the textarea |
| p-smarttextarea-typed | Class name of the copies of the typed text in the mirror, transparent |
| p-smarttextarea-suggestion | Class name of the suggestion, the ghost text |
| p-smarttextarea-key | Class name of the accept key shown after the suggestion |

### Design Tokens

| Token | CSS Variable | Description |
|-------|--------------|-------------|
| smarttextarea.suggestion.color | --p-smarttextarea-suggestion-color | Color of the suggestion, the ghost text |
| smarttextarea.suggestion.font.style | --p-smarttextarea-suggestion-font-style | Font style of the suggestion, the ghost text |
| smarttextarea.suggestion.opacity | --p-smarttextarea-suggestion-opacity | Opacity of the suggestion, the ghost text |
| smarttextarea.key.gap | --p-smarttextarea-key-gap | Gap of the accept key shown after the suggestion |
| smarttextarea.key.padding | --p-smarttextarea-key-padding | Padding of the accept key shown after the suggestion |
| smarttextarea.key.border.radius | --p-smarttextarea-key-border-radius | Border radius of the accept key shown after the suggestion |
| smarttextarea.key.border.color | --p-smarttextarea-key-border-color | Border color of the accept key shown after the suggestion |
| smarttextarea.key.background | --p-smarttextarea-key-background | Background of the accept key shown after the suggestion |
| smarttextarea.key.color | --p-smarttextarea-key-color | Color of the accept key shown after the suggestion |
| smarttextarea.key.font.size | --p-smarttextarea-key-font-size | Font size of the accept key shown after the suggestion |

