# Tag input

- Entry point: `@koobiq/components/tags`
- NgModule: `KbqTagsModule`
- Page: https://koobiq.io/en/components/tag-input/overview

## Overview

Tag Input lets users enter multiple values as tags and supports keyboard navigation, selection, and removal.

**Example: Tag input overview** (`tag-input-overview`)

```ts tag-input-overview-example.ts
import { moveItemInArray } from '@angular/cdk/drag-drop';
import { COMMA, ENTER, SEMICOLON, SPACE, TAB } from '@angular/cdk/keycodes';
import { ChangeDetectionStrategy, Component, ElementRef, model, viewChild } from '@angular/core';
import { KbqComponentColors } from '@koobiq/components/core';
import { KbqIconModule } from '@koobiq/components/icon';
import { KbqInputModule } from '@koobiq/components/input';
import {
    KbqTagEvent,
    KbqTagInput,
    KbqTagInputEvent,
    KbqTagListDroppedEvent,
    KbqTagsModule
} from '@koobiq/components/tags';

const getTags = () => Array.from({ length: 3 }, (_, i) => ({ value: `Tag ${i}` }));

@Component({
    selector: 'tag-input-overview-example',
    imports: [KbqTagsModule, KbqIconModule, KbqInputModule],
    template: `
        <kbq-form-field>
            <kbq-tag-list #tagList="kbqTagList" removable draggable (dropped)="dropped($event)">
                @for (tag of tags(); track tag) {
                    <kbq-tag [value]="tag" (removed)="removed($event)">
                        {{ tag.value }}
                        <i kbq-icon-button="kbq-xmark-s_16" kbqTagRemove (click)="afterRemove()"></i>
                    </kbq-tag>
                }

                <input
                    autocomplete="off"
                    kbqInput
                    placeholder="New tag"
                    [kbqTagInputSeparatorKeyCodes]="separators"
                    [kbqTagInputFor]="tagList"
                    (kbqTagInputTokenEnd)="create($event)"
                />

                <kbq-cleaner />
            </kbq-tag-list>
        </kbq-form-field>
    `,
    styles: `
        :host {
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: var(--kbq-size-m);
            min-height: var(--kbq-size-xxl);
            margin: var(--kbq-size-5xl);
        }
    `,
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class TagInputOverviewExample {
    protected readonly colors = KbqComponentColors;
    protected readonly removable = model(true);
    protected readonly tags = model(getTags());
    protected readonly separators = [COMMA, SPACE, SEMICOLON, ENTER, TAB];
    private readonly input = viewChild.required(KbqTagInput, { read: ElementRef });

    protected removed(event: KbqTagEvent): void {
        this.tags.update((tags) => {
            const index = tags.indexOf(event.tag.value);

            tags.splice(index, 1);

            console.log(`Tag #${index} was removed:`, event);

            return tags;
        });
    }

    protected create({ input, value = '' }: KbqTagInputEvent): void {
        if (value) {
            this.tags.update((tags) => {
                tags.push({ value });

                return tags;
            });

            input.value = '';
        }
    }

    protected dropped({ previousIndex, currentIndex }: KbqTagListDroppedEvent): void {
        moveItemInArray(this.tags(), previousIndex, currentIndex);
        this.focusInput();
    }

    protected afterRemove(): void {
        this.focusInput();
    }

    private focusInput(): void {
        this.input().nativeElement.focus();
    }
}
```

### Tag removal

Tag removal order:

- If there are selected tags, all of them will be removed.
- If there are no selected tags, the focused tag will be removed.

Tags can be removed in several ways:

- Click on the remove icon (`kbqTagRemove` directive) inside the tag.
- Press `Delete` or `Backspace` key.
- Click on the reset control, which removes every tag except the disabled ones.
- Programmatic removal through the component [API](https://koobiq.io/en/components/tag.md).

The removal option is configured using the `removable` attribute (enabled by default). A disabled tag does not show its remove icon, and a list with `removable="false"` has no reset control either.

**Example: Tag input removable** (`tag-input-removable`)

```ts tag-input-removable-example.ts
import { COMMA, ENTER, SEMICOLON, SPACE, TAB } from '@angular/cdk/keycodes';
import { ChangeDetectionStrategy, Component, ElementRef, model, viewChild } from '@angular/core';
import { KbqComponentColors } from '@koobiq/components/core';
import { KbqIconModule } from '@koobiq/components/icon';
import { KbqInputModule } from '@koobiq/components/input';
import { KbqTagEvent, KbqTagInput, KbqTagInputEvent, KbqTagsModule } from '@koobiq/components/tags';

const getTags = () => Array.from({ length: 3 }, (_, i) => ({ value: `Removable tag ${i}` }));

@Component({
    selector: 'tag-input-removable-example',
    imports: [KbqTagsModule, KbqIconModule, KbqInputModule],
    template: `
        <kbq-form-field>
            <kbq-tag-list #tagList="kbqTagList" removable>
                @for (tag of tags(); track tag) {
                    <kbq-tag [value]="tag" (removed)="removed($event)">
                        {{ tag.value }}
                        <i kbq-icon-button="kbq-xmark-s_16" kbqTagRemove (click)="afterRemove()"></i>
                    </kbq-tag>
                }

                <input
                    autocomplete="off"
                    kbqInput
                    placeholder="New tag"
                    [kbqTagInputSeparatorKeyCodes]="separators"
                    [kbqTagInputFor]="tagList"
                    (kbqTagInputTokenEnd)="create($event)"
                />

                <kbq-cleaner />
            </kbq-tag-list>
        </kbq-form-field>
    `,
    styles: `
        :host {
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: var(--kbq-size-m);
            min-height: var(--kbq-size-xxl);
            margin: var(--kbq-size-5xl);
        }
    `,
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class TagInputRemovableExample {
    protected readonly colors = KbqComponentColors;
    protected readonly removable = model(true);
    protected readonly tags = model(getTags());
    protected readonly separators = [COMMA, SPACE, SEMICOLON, ENTER, TAB];
    private readonly input = viewChild.required(KbqTagInput, { read: ElementRef });

    protected removed(event: KbqTagEvent): void {
        this.tags.update((tags) => {
            const index = tags.indexOf(event.tag.value);

            tags.splice(index, 1);

            console.log(`Tag #${index} was removed:`, event);

            return tags;
        });
    }

    protected create({ input, value = '' }: KbqTagInputEvent): void {
        if (value) {
            this.tags.update((tags) => {
                tags.push({ value });

                return tags;
            });

            input.value = '';
        }
    }

    protected afterRemove(): void {
        this.input().nativeElement.focus();
    }
}
```

The reset control needs no handler of its own — it removes the tags through the same `removed` output as the remove icon inside a tag. Which tags it removes is set by the `clearPredicate` attribute: `[clearPredicate]="clearEverything"` and `clearEverything = () => true` clear the disabled ones too.

**Example: Tag input cleaner with disabled tags** (`tag-input-cleaner-with-disabled`)

```ts tag-input-cleaner-with-disabled-example.ts
import { COMMA, ENTER } from '@angular/cdk/keycodes';
import { ChangeDetectionStrategy, Component, model } from '@angular/core';
import { KbqIconModule } from '@koobiq/components/icon';
import { KbqInputModule } from '@koobiq/components/input';
import { KbqTag, KbqTagEvent, KbqTagInputEvent, KbqTagsModule } from '@koobiq/components/tags';

/** Tags the user is not allowed to take off. */
const lockedTags = ['Beta'];

@Component({
    selector: 'tag-input-cleaner-with-disabled-example',
    imports: [KbqIconModule, KbqInputModule, KbqTagsModule],
    template: `
        <kbq-form-field>
            <kbq-tag-list #keptList="kbqTagList">
                @for (tag of kept(); track tag) {
                    <kbq-tag [value]="tag" [disabled]="isLocked(tag)" (removed)="removedFromKept($event)">
                        {{ tag }}
                        <i kbq-icon-button="kbq-xmark-s_16" kbqTagRemove></i>
                    </kbq-tag>
                }

                <input
                    autocomplete="off"
                    kbqInput
                    placeholder="Kept"
                    [kbqTagInputFor]="keptList"
                    [kbqTagInputSeparatorKeyCodes]="separators"
                    (kbqTagInputTokenEnd)="createInKept($event)"
                />

                <kbq-cleaner />
            </kbq-tag-list>
        </kbq-form-field>

        <kbq-form-field>
            <kbq-tag-list #clearedList="kbqTagList" [clearPredicate]="clearEverything">
                @for (tag of cleared(); track tag) {
                    <kbq-tag [value]="tag" [disabled]="isLocked(tag)" (removed)="removedFromCleared($event)">
                        {{ tag }}
                        <i kbq-icon-button="kbq-xmark-s_16" kbqTagRemove></i>
                    </kbq-tag>
                }

                <input
                    autocomplete="off"
                    kbqInput
                    placeholder="Cleared"
                    [kbqTagInputFor]="clearedList"
                    [kbqTagInputSeparatorKeyCodes]="separators"
                    (kbqTagInputTokenEnd)="createInCleared($event)"
                />

                <kbq-cleaner />
            </kbq-tag-list>
        </kbq-form-field>
    `,
    styles: `
        :host {
            display: flex;
            justify-content: center;
            gap: var(--kbq-size-l);
            padding: var(--kbq-size-l);
        }

        .kbq-form-field {
            width: 240px;
        }
    `,
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class TagInputCleanerWithDisabledExample {
    protected readonly separators = [COMMA, ENTER];
    protected readonly kept = model(['Alpha', 'Beta', 'Gamma']);
    protected readonly cleared = model(['Alpha', 'Beta', 'Gamma']);

    /** Opts out of the default, which leaves the disabled tags in place. */
    protected readonly clearEverything = (_tag: KbqTag) => true;

    protected isLocked(tag: string): boolean {
        return lockedTags.includes(tag);
    }

    protected createInKept({ input, value = '' }: KbqTagInputEvent): void {
        if (value) {
            this.kept.update((tags) => [...tags, value]);
            input.value = '';
        }
    }

    protected createInCleared({ input, value = '' }: KbqTagInputEvent): void {
        if (value) {
            this.cleared.update((tags) => [...tags, value]);
            input.value = '';
        }
    }

    protected removedFromKept({ tag }: KbqTagEvent): void {
        this.kept.update((tags) => tags.filter((value) => value !== tag.value));
    }

    protected removedFromCleared({ tag }: KbqTagEvent): void {
        this.cleared.update((tags) => tags.filter((value) => value !== tag.value));
    }
}
```

### Tag selection

Tags can be selected in several ways:

- Click on a tag while holding `Ctrl`.
- Click on a tag while holding `Shift` to change the selection range from the anchor tag to the clicked tag.
- Press `Shift` + `←` / `→` to expand or shrink the range.
- Press `Ctrl+A` key combination.
- `Space` when the tag is focused.
- Programmatic selection through the component [API](https://koobiq.io/en/components/tag.md).

Pointer and keyboard interactions change the same range relative to its initial tag. When the range shrinks, tags outside it are deselected. Disabled tags remain unchanged.

The selection option is configured using the `selectable` attribute (enabled by default).

### Editing

To enable editing mode, you need to set the `editable` property for `kbq-tag-list` or individual `kbq-tag`.

Enter editing mode:

- On double click on the tag.
- On pressing `Enter` or `F2` key (when tag is focused).

Save changes:

- On pressing `Enter` key.
- On clicking the confirmation button (`kbqTagEditSubmit` directive).

Cancel changes:

- On pressing `Escape` key.
- On focus loss.

In editing mode, the tag transforms into an input field and remains at the same position within the control.

**Example: Tag input editable** (`tag-input-editable`)

```ts tag-input-editable-example.ts
import { COMMA, ENTER, SEMICOLON, SPACE, TAB } from '@angular/cdk/keycodes';
import { ChangeDetectionStrategy, Component, ElementRef, model, viewChild } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { KbqComponentColors } from '@koobiq/components/core';
import { KbqIconModule } from '@koobiq/components/icon';
import { KbqInputModule } from '@koobiq/components/input';
import { KbqTagEditChange, KbqTagEvent, KbqTagInput, KbqTagInputEvent, KbqTagsModule } from '@koobiq/components/tags';
import { KbqTitleModule } from '@koobiq/components/title';

const getTags = () => Array.from({ length: 3 }, (_, i) => ({ value: `Editable tag ${i}` }));

@Component({
    selector: 'tag-input-editable-example',
    imports: [KbqTagsModule, KbqIconModule, FormsModule, KbqInputModule, KbqTitleModule],
    template: `
        <kbq-form-field>
            <kbq-tag-list #tagList="kbqTagList" editable>
                @for (tag of tags(); track tag) {
                    <kbq-tag
                        kbq-title
                        [value]="tag"
                        (editChange)="editChange($event, $index)"
                        (removed)="removed($event)"
                    >
                        {{ tag.value }}
                        <input kbqInput kbqTagEditInput [(ngModel)]="editInputModel" />
                        @if (editInputModel().length === 0) {
                            <i kbq-icon-button="kbq-xmark-s_16" kbqTagEditSubmit [color]="color.Theme"></i>
                        } @else {
                            <i kbq-icon-button="kbq-check-s_16" kbqTagEditSubmit [color]="color.Theme"></i>
                        }
                        <i kbq-icon-button="kbq-xmark-s_16" kbqTagRemove (click)="afterRemove()"></i>
                    </kbq-tag>
                }

                <input
                    autocomplete="off"
                    kbqInput
                    placeholder="New tag"
                    [kbqTagInputSeparatorKeyCodes]="separators"
                    [kbqTagInputFor]="tagList"
                    (kbqTagInputTokenEnd)="create($event)"
                />

                <kbq-cleaner />
            </kbq-tag-list>
        </kbq-form-field>
    `,
    styles: `
        :host {
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: var(--kbq-size-xl);
            margin: var(--kbq-size-xl);
        }
    `,
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class TagInputEditableExample {
    protected readonly color = KbqComponentColors;
    protected readonly tags = model(getTags());
    private readonly input = viewChild.required(KbqTagInput, { read: ElementRef });
    protected readonly editInputModel = model<string>('');
    protected readonly separators = [COMMA, SPACE, SEMICOLON, ENTER, TAB];

    protected editChange({ reason, type, tag }: KbqTagEditChange, index: number): void {
        switch (type) {
            case 'start': {
                console.info(`Tag #${index} edit was started. Reason: "${reason}".`);

                this.editInputModel.set(tag.value.value);

                break;
            }
            case 'cancel': {
                console.info(`Tag #${index} edit was canceled. Reason: "${reason}".`);

                this.editInputModel.set('');

                this.focusInput();

                break;
            }
            case 'submit': {
                console.info(`Tag #${index} edit was submitted. Reason: "${reason}".`);

                if (!this.editInputModel()) {
                    tag.remove();
                } else {
                    this.tags.update((tags) => {
                        tags[index].value = this.editInputModel();

                        return tags;
                    });
                    this.editInputModel.set('');
                }

                this.focusInput();

                break;
            }
            default:
        }
    }

    protected removed(event: KbqTagEvent): void {
        this.tags.update((tags) => {
            const index = tags.indexOf(event.tag.value);

            tags.splice(index, 1);

            console.info(`Tag #${index} was removed.`);

            return [...tags];
        });
    }

    protected create({ input, value = '' }: KbqTagInputEvent): void {
        if (value) {
            this.tags.update((tags) => {
                tags.push({ value });

                return tags;
            });

            input.value = '';
        }
    }

    protected afterRemove(): void {
        this.focusInput();
    }

    private focusInput(): void {
        this.input().nativeElement.focus();
    }
}
```

### Drag and drop

To enable tag reordering, you need to set the `draggable` property for `kbq-tag-list`.

**Example: Tag input draggable** (`tag-input-draggable`)

```ts tag-input-draggable-example.ts
import { moveItemInArray } from '@angular/cdk/drag-drop';
import { COMMA, ENTER, SEMICOLON, SPACE, TAB } from '@angular/cdk/keycodes';
import { ChangeDetectionStrategy, Component, ElementRef, model, viewChild } from '@angular/core';
import { KbqIconModule } from '@koobiq/components/icon';
import { KbqInputModule } from '@koobiq/components/input';
import {
    KbqTagEvent,
    KbqTagInput,
    KbqTagInputEvent,
    KbqTagListDroppedEvent,
    KbqTagsModule
} from '@koobiq/components/tags';

const getTags = () => Array.from({ length: 3 }, (_, id) => ({ id, value: `Draggable tag ${id}` }));

@Component({
    selector: 'tag-input-draggable-example',
    imports: [KbqTagsModule, KbqIconModule, KbqInputModule],
    template: `
        <kbq-form-field>
            <kbq-tag-list #tagList="kbqTagList" draggable (dropped)="dropped($event)">
                @for (tag of tags(); track tag.id) {
                    <kbq-tag [value]="tag.value" (removed)="removed($event)">
                        {{ tag.value }}
                        <i kbq-icon-button="kbq-xmark-s_16" kbqTagRemove (click)="afterRemove()"></i>
                    </kbq-tag>
                }

                <input
                    autocomplete="off"
                    kbqInput
                    placeholder="New tag"
                    [kbqTagInputFor]="tagList"
                    [kbqTagInputSeparatorKeyCodes]="separators"
                    (kbqTagInputTokenEnd)="create($event)"
                />

                <kbq-cleaner />
            </kbq-tag-list>
        </kbq-form-field>
    `,
    styles: `
        :host {
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: var(--kbq-size-m);
            margin: var(--kbq-size-5xl);
        }
    `,
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class TagInputDraggableExample {
    protected readonly tags = model(getTags());
    private readonly input = viewChild.required(KbqTagInput, { read: ElementRef });
    protected readonly separators = [COMMA, SPACE, SEMICOLON, ENTER, TAB];

    protected dropped(event: KbqTagListDroppedEvent): void {
        moveItemInArray(this.tags(), event.previousIndex, event.currentIndex);
        this.focusInput();
    }

    protected create({ input, value = '' }: KbqTagInputEvent): void {
        if (value) {
            this.tags.update((tags) => {
                tags.push({ id: tags.length, value });

                return tags;
            });

            input.value = '';
        }
    }

    protected removed(event: KbqTagEvent): void {
        this.tags.update((tags) => {
            const index = tags.findIndex(({ value }) => value === event.tag.value);

            tags.splice(index, 1);

            console.log(`Tag #${index} was removed:`, event);

            return tags;
        });
    }

    protected afterRemove(): void {
        this.focusInput();
    }

    private focusInput(): void {
        this.input().nativeElement.focus();
    }
}
```

### Separators

By default, a tag is created on `Enter`. Additional separator keys are set via `kbqTagInputSeparatorKeyCodes` and apply both while typing and when pasting from the clipboard.

If a separator should only apply on paste (e.g. a space, which is a common character inside a tag), mark it with `appliesTo: ['paste']`. Separators without a `key` (e.g. `/\s+/` for any run of whitespace) are paste-only by default, since no keystroke can ever match them.

Application- or module-wide defaults are set via `kbqTagsDefaultOptionsProvider`:

```ts
import { ENTER } from '@koobiq/components/core';
import { kbqTagsDefaultOptionsProvider } from '@koobiq/components/tags';

@NgModule({
    providers: [
        kbqTagsDefaultOptionsProvider({
            separatorKeyCodes: [ENTER],
            separators: [
                { symbol: /\r?\n/, key: 'Enter', keyCode: ENTER, appliesTo: ['input', 'paste'] },
                { symbol: /\s+/, appliesTo: ['paste'] } // paste-only — splits on any whitespace
            ]
        })
    ]
})
```

### Validation

Validators belong on `<kbq-tag-list>`: the tag list is the form control for the whole set of tags, while the input is only a text entry helper. The control value is the array of tags, so a single set of validators covers both the number of tags and the content of each one.

A `[formControl]` or `[ngModel]` of its own on `<input kbqTagInputFor>` is still fine — that is how the typed text can drive autocomplete filtering, for example. The library simply does not consider validators attached to that control: it neither checks them nor puts the field into the error state.

Validators do not prevent a tag from being added: the tag is added and the field goes into the error state — the same way for typing and for pasting from the clipboard. To keep an invalid value out of the list, filter it in the `(kbqTagInputTokenEnd)` handler. In-place tag editing does not go through that handler — reject a value there with `preventEditSubmit`.

When the error becomes visible is controlled by [ErrorStateMatcher](https://koobiq.io/en/other/validation.md), and by default happens once the control is invalid and either touched or the form has been submitted.

**Example: Tag input with form control validators** (`tag-input-with-form-control-validators`)

```ts tag-input-with-form-control-validators-example.ts
import { ChangeDetectionStrategy, Component, ElementRef, viewChild } from '@angular/core';
import {
    AbstractControl,
    FormControl,
    ReactiveFormsModule,
    ValidationErrors,
    ValidatorFn,
    Validators
} from '@angular/forms';
import { KbqIconModule } from '@koobiq/components/icon';
import { KbqInputModule } from '@koobiq/components/input';
import { KbqTagInput, KbqTagInputEvent, KbqTagsModule } from '@koobiq/components/tags';

const MAX_TAG_COUNT = 5;
const LATIN_PATTERN = /^[a-zA-Z]+$/;

/** Validates every tag separately, reporting the offending ones back to the template. */
const latinValidator = (): ValidatorFn => {
    return ({ value }: AbstractControl<string[] | null>): ValidationErrors | null => {
        const invalidTags = (value || []).filter((tag) => !LATIN_PATTERN.test(tag));

        return invalidTags.length ? { latin: { invalidTags } } : null;
    };
};

/** @title Tag input with form control validators */
@Component({
    selector: 'tag-input-with-form-control-validators-example',
    imports: [
        KbqInputModule,
        KbqTagsModule,
        KbqIconModule,
        ReactiveFormsModule
    ],
    template: `
        <kbq-form-field>
            <kbq-tag-list #tagList="kbqTagList" [formControl]="formControl">
                @for (tag of formControl.value; track $index) {
                    <kbq-tag [value]="tag" (removed)="removeTag(tag)">
                        {{ tag }}
                        <i kbq-icon-button="kbq-xmark-s_16" kbqTagRemove (click)="afterRemove()"></i>
                    </kbq-tag>
                }

                <input
                    autocomplete="off"
                    kbqInput
                    placeholder="New tag"
                    [kbqTagInputFor]="tagList"
                    (kbqTagInputTokenEnd)="createTag($event)"
                />

                <kbq-cleaner />
            </kbq-tag-list>

            <kbq-hint>Only latin letters, up to {{ maxTagCount }} tags</kbq-hint>

            @if (formControl.hasError('required')) {
                <kbq-error>Field is required</kbq-error>
            }

            @if (formControl.getError('maxlength'); as error) {
                <kbq-error>No more than {{ error.requiredLength }} tags</kbq-error>
            }

            @if (formControl.getError('latin'); as error) {
                <kbq-error>Invalid tags: {{ error.invalidTags.join(', ') }}</kbq-error>
            }
        </kbq-form-field>
    `,
    styles: `
        :host {
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: var(--kbq-size-m);
            min-height: var(--kbq-size-xxl);
            margin: var(--kbq-size-5xl);
        }
    `,
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class TagInputWithFormControlValidatorsExample {
    private readonly input = viewChild.required(KbqTagInput, { read: ElementRef });
    protected readonly maxTagCount = MAX_TAG_COUNT;
    protected readonly formControl = new FormControl<string[]>(
        ['Koobiq', 'Angular', 'Design'],
        [Validators.required, Validators.maxLength(MAX_TAG_COUNT), latinValidator()]
    );

    protected removeTag(tag: string): void {
        const tags = [...(this.formControl.value || [])];
        const index = tags.indexOf(tag);

        if (index >= 0) {
            tags.splice(index, 1);
            this.formControl.setValue(tags);
        }
    }

    protected createTag({ value, input }: KbqTagInputEvent): void {
        if (value) {
            this.formControl.setValue([...(this.formControl.value || []), value]);
        }

        input.value = '';
    }

    protected afterRemove(): void {
        this.input().nativeElement.focus();
    }
}
```

### Keyboard navigation

#### Focus in empty input area

| Key                         | Action                                         |
| --------------------------- | ---------------------------------------------- |
| Backspace / ← / Shift + Tab | Move focus to the last tag.                    |
| Ctrl + A                    | Select all tags and set focus to the last one. |

#### Focus on tag

| Key                | Action                           |
| ------------------ | -------------------------------- |
| ← / →              | Move focus to previous/next tag. |
| Shift + ← / →      | Change the range and move focus. |
| Space              | Select/deselect tag.             |
| Delete / Backspace | Remove tag.                      |
| F2 / Enter         | Start editing.                   |
| Ctrl + A           | Select all tags.                 |
| Home / End         | Move focus to first/last tag.    |

#### Tag editing mode

| Key   | Action          |
| ----- | --------------- |
| Enter | Save changes.   |
| Esc   | Cancel changes. |

## API

### Components

#### KbqTag (component)

```ts
@Component({
    selector: 'kbq-tag, [kbq-tag], kbq-basic-tag, [kbq-basic-tag]',
    exportAs: 'kbqTag'
})
class KbqTag extends KbqColorDirective implements IFocusableOption, KbqTitleTextRef {
    readonly editable = input<boolean | undefined>();
    readonly preventEditSubmit = input<boolean>(false);
    readonly selected = input(false);
    value = input<NonNullable<unknown> | null | undefined>();
    readonly selectable = input(false);
    readonly removable = input(true);
    tabindex = input<number | null | undefined>();
    disabled = input<boolean | undefined>();
    readonly color = input<T | null | undefined>();
    readonly editChange = output<KbqTagEditChange>();
    readonly selectionChange = output<KbqTagSelectionChange>();
    readonly destroyed = output<KbqTagEvent>();
    readonly removed = output<KbqTagEvent>();
    changeDetectorRef: ChangeDetectorRef;
    readonly contentChildren: Signal<readonly KbqIcon[]>;
    readonly avatar: Signal<KbqTagAvatar | undefined>;
    readonly trailingIcon: Signal<KbqTagTrailingIcon | undefined>;
    readonly removeIcon: Signal<any>;
    get canRemove(): boolean;
    get colorClassName(): string;
    select(): void;
    deselect(): void;
    toggleSelected(isUserInput?: boolean): boolean;
    focus(): void;
    remove(): void;
    setDefaultColor(color: T): void;
}
```

- `[editable]`: `boolean | undefined` — Whether the tag is editable.
- `[preventEditSubmit]`: `boolean` — Whether the tag edits can't be submitted.
- `[selected]`: `Signal<boolean>` — Whether the tag is selected.
- `[value]`: `NonNullable<unknown> | null | undefined` — The value of the tag. Defaults to the content inside `<kbq-tag>` tags.
- `[selectable]`: `Signal<boolean>` — Whether the tag is selectable.
- `[removable]`: `Signal<boolean>` — Determines whether the tag is removable.
- `[tabindex]`: `number | null | undefined` — Tab order of the tag.
- `[disabled]`: `boolean | undefined` — Whether the tag is disabled.
- `[localeOverrides]`: `KbqPartialLocaleData | undefined` — Localized strings for this element and its subtree, keyed by locale section. Every key is optional at
  every depth.
- `[color]`: `T | null | undefined` — Color of the component. A value set in code holds until the input changes, and the default color is used
  while both are unset or falsy.
- `(editChange)`: `KbqTagEditChange` — Emits event when the tag is edited.
- `(selectionChange)`: `KbqTagSelectionChange` — Emitted when the tag is selected or deselected.
- `(destroyed)`: `KbqTagEvent` — Emitted when the tag is destroyed and leaving the DOM.
- `(removed)`: `KbqTagEvent` — Emitted when a tag is to be removed.
  Fires on programmatic and UI removal (click or keyboard).
- `avatar`: `Signal<KbqTagAvatar | undefined>` — The tag avatar
- `trailingIcon`: `Signal<KbqTagTrailingIcon | undefined>` — The tag's trailing icon.
- `removeIcon`: `Signal<any>` — The tag's remove toggler.
- `canRemove`: `boolean` — Whether the user may remove this tag through the controls the tag itself offers — the remove
  control and the `Delete` key. A disabled tag offers neither.

  This is the affordance, not the channel: `remove()` stays open so the list can still clear a
  disabled tag when `clearPredicate` asks for it.
- `colorClassName`: `string` — current class name of color
- `select()`: `void` — Selects the tag.
- `deselect()`: `void` — Deselects the tag.
- `toggleSelected()`: `boolean` — Toggles the current selected state of the tag.
- `focus()`: `void` — Focuses the tag.
- `remove()`: `void` — Allows for programmatic removal of the tag. Called by the KbqTagList when the DELETE or
  BACKSPACE keys are pressed.

  Informs any listeners of the removal request. Does not remove the tag from the DOM.
- `setDefaultColor()`: `void` — this color will be used as a default value. For example [color]="'' | false | undefined | null".

#### KbqTagList (component)

```ts
@Component({ selector: 'kbq-tag-list', exportAs: 'kbqTagList' })
class KbqTagList implements KbqFormFieldControl<any>, ControlValueAccessor, CanUpdateErrorState {
    draggable = input<boolean | undefined>();
    readonly selectable = input<boolean>(true);
    readonly editable = input<boolean>(false);
    readonly clearPredicate = input<(tag: KbqTag) => boolean>(
        (tag) => !tag.disabled
    );
    readonly removable = input<boolean>(true);
    readonly errorStateMatcher = input<ErrorStateMatcher>();
    readonly dropped = output<KbqTagListDroppedEvent>();
    readonly change = output<KbqTagListChange>();
    defaultErrorStateMatcher: ErrorStateMatcher;
    parentForm: NgForm | null;
    parentFormGroup: FormGroupDirective | null;
    ngControl: NgControl;
    readonly focused: Signal<boolean>;
    notifyPendingTagChange(): void;
    focus(): void;
    blur(): void;
    markAsTouched(): void;
}
```

- `[draggable]`: `boolean | undefined` — Whether the tags in the list can be reordered by dragging.
- `[selectable]`: `boolean` — Whether or not this tag list is selectable. When a tag list is not selectable,
  the selected states for all the tags inside the tag list are always ignored.
- `[editable]`: `boolean` — Whether the tags in the list are editable.
- `[clearPredicate]`: `(tag: KbqTag) => boolean` — Decides which tags the projected `KbqCleaner` removes: return `true` to clear the tag, `false` to
  keep it. Disabled tags are kept by default. Bind a stable reference — a new function on every change
  detection re-runs the predicate over every tag.

  A tag the list does not allow to be removed is never offered, whatever the predicate answers.
- `[removable]`: `boolean` — Whether the tags in the list are removable.
- `[errorStateMatcher]`: `ErrorStateMatcher` — An object used to control when error messages are shown.
- `(dropped)`: `KbqTagListDroppedEvent` — Emits when the user drops tag inside tag list container.
- `(change)`: `KbqTagListChange` — Event emitted when the selected tag list value has been changed by the user.
- `focused`: `Signal<boolean>` — Whether any tags or the kbqTagInput inside of this tag-list has focus.
- `notifyPendingTagChange()`: `void` — Notifies that the next `tags.changes` emission is UI-initiated.
- `focus()`: `void` — Focuses the tag list. If there is a tag input, focuses that instead.
- `blur()`: `void` — When blurred, mark the field as touched when focus moved outside the tag list.
- `markAsTouched()`: `void` — Mark the field as touched

### Directives

#### KbqTagEditInput (directive)

Directive to add input behavior for the editable tag.

```ts
@Directive({ selector: '[kbqTagEditInput]', exportAs: 'kbqTagEditInput' })
class KbqTagEditInput {}
```

#### KbqTagEditSubmit (directive)

Directive to add submit behavior for the editable tag.

```ts
@Directive({ selector: '[kbqTagEditSubmit]', exportAs: 'kbqTagEditSubmit' })
class KbqTagEditSubmit {}
```

#### KbqTagInput (directive)

Directive that adds tag-specific behaviors to an input element inside `<kbq-form-field>`.
May be placed inside or outside of an `<kbq-tag-list>`.

```ts
@Directive({
    selector: 'input[kbqTagInputFor]',
    exportAs: 'kbqTagInput, kbqTagInputFor'
})
class KbqTagInput implements KbqTagTextControl {
    readonly separatorKeyCodes = input<number[]>(
        this.defaultOptions.separatorKeyCodes,
        { alias: 'kbqTagInputSeparatorKeyCodes' }
    );
    readonly distinct = input<boolean>(false);
    readonly placeholder = input<string>('');
    readonly id = input<string>(
        inject(_IdGenerator).getId('kbq-tag-list-input-')
    );
    readonly tagList = input<KbqTagList | undefined>(undefined, {
        alias: 'kbqTagInputFor'
    });
    readonly addOnBlur = input<boolean>(true, {
        alias: 'kbqTagInputAddOnBlur'
    });
    readonly addOnPaste = input<boolean>(
        this.defaultOptions.addOnPaste ?? true,
        { alias: 'kbqTagInputAddOnPaste' }
    );
    disabled = input<boolean | undefined>();
    readonly tagEnd = output<KbqTagInputEvent>({
        alias: 'kbqTagInputTokenEnd'
    });
    readonly autofilled: Signal<boolean>;
    readonly empty: Signal<boolean>;
    focus(): void;
}
```

- `[kbqTagInputSeparatorKeyCodes]`: `number[]` — The list of key codes that will trigger a tagEnd event.

  Defaults to `[ENTER]`.
- `[distinct]`: `boolean` — A value indicating whether allow/prevent tags duplication
- `[placeholder]`: `string` — The input's placeholder text.
- `[id]`: `string` — Unique id for the input.
- `[kbqTagInputFor]`: `KbqTagList | undefined` — Register input for tag list.
- `[kbqTagInputAddOnBlur]`: `boolean` — Whether or not the tagEnd event will be emitted when the input is blurred.
- `[kbqTagInputAddOnPaste]`: `boolean` — Whether the tagEnd event will be emitted when the text pasted. Defaults to `addOnPaste` of
  `KBQ_TAGS_DEFAULT_OPTIONS`, or `true`.
- `[disabled]`: `boolean | undefined` — Whether the input is disabled.
- `(kbqTagInputTokenEnd)`: `KbqTagInputEvent` — Emitted when a tag is to be added.
- `autofilled`: `Signal<boolean>` — Whether the control's value was filled in by the browser.
- `empty`: `Signal<boolean>` — Whether the input is empty.
- `focus()`: `void` — Focuses the input.

#### KbqTagPrefix (directive)

Marks content to be projected into the prefix (leading) slot of a tag.

```ts
@Directive({ selector: '[kbqTagPrefix]' })
class KbqTagPrefix {}
```

#### KbqTagRemove (directive)

Example:

    `<kbq-tag>
      <kbq-icon kbqTagRemove>cancel</kbq-icon>
    </kbq-tag>`

You *may* use a custom icon, but you may need to override the `kbq-tag-remove` positioning
styles to properly center the icon within the tag.

```ts
@Directive({ selector: '[kbqTagRemove]' })
class KbqTagRemove {
    readonly ariaLabel = input<string | undefined>(undefined, {
        alias: 'aria-label'
    });
}
```

- `[aria-label]`: `string | undefined` — Accessible name of the button. Defaults to the localized "Remove".

#### KbqTagSuffix (directive)

Marks content to be projected into the suffix (trailing) slot of a tag.

```ts
@Directive({ selector: '[kbqTagSuffix]' })
class KbqTagSuffix {}
```

### Classes

#### KbqTagEditChange (class)

Event object emitted by KbqTag when the tag is edited.

```ts
class KbqTagEditChange {
    readonly tag: KbqTag;
    readonly type: "start" | "cancel" | "submit";
    readonly reason: string;
    constructor(
        tag: KbqTag,
        type: "start" | "cancel" | "submit",
        reason: string
    );
}
```

#### KbqTagListChange (class)

Change event object that is emitted when the tag list value has changed.

```ts
class KbqTagListChange {
    source: KbqTagList;
    value: any;
    constructor(source: KbqTagList, value: any);
}
```

#### KbqTagSelectionChange (class)

Event object emitted by KbqTag when selected or deselected.

```ts
class KbqTagSelectionChange {
    source: KbqTag;
    selected: boolean;
    isUserInput: boolean;
    constructor(
        source: KbqTag,
        selected: boolean,
        isUserInput?: boolean
    );
}
```

### Types

#### KbqTagEvent (type)

Event object emitted by KbqTag.

```ts
type KbqTagEvent = {
    tag: KbqTag;
};
```

#### KbqTagFocusEvent (type)

Event object emitted when the KbqTag is focused.

```ts
type KbqTagFocusEvent = KbqTagEvent & {
    origin: FocusOrigin;
};
```

#### KbqTagInputEvent (interface)

Represents an input event on a `kbqTagInput`.

```ts
interface KbqTagInputEvent {
    input: HTMLInputElement;
    value: string;
}
```

- `input`: `HTMLInputElement` — The native `<input>` element that the event is being fired for.
- `value`: `string` — The value of the input.

#### KbqTagListDroppedEvent (type)

```ts
type KbqTagListDroppedEvent = Pick<CdkDragDrop<unknown>, 'event' | 'previousIndex' | 'currentIndex'> & {
    tag: KbqTag;
};
```

#### KbqTagsDefaultOptions (interface)

Default options for the tags module that can be overridden.

```ts
interface KbqTagsDefaultOptions {
    separatorKeyCodes: number[];
    separators?: KbqTagSeparator[];
    addOnPaste?: boolean;
}
```

- `separatorKeyCodes`: `number[]` — The list of key codes that will trigger a tagEnd event.
- `separators?`: `KbqTagSeparator[]` — Custom separator definitions to use instead of the built-in defaults.
- `addOnPaste?`: `boolean` — Whether the tagEnd event will be emitted when text is pasted.

#### KbqTagSeparator (interface)

Defines a character or pattern that ends a tag, and the contexts in which it applies.

```ts
interface KbqTagSeparator {
    symbol: RegExp;
    key?: string;
    keyCode?: number;
    appliesTo?: KbqTagSeparatorContext[];
}
```

- `symbol`: `RegExp` — Regular expression used to match/split this separator in text.
- `key?`: `string` — `KeyboardEvent.key` that triggers this separator while typing.
  Omit for separators with no single-keystroke equivalent (e.g. a run of whitespace) —
  those are implicitly paste-only, since they can never match a `keydown`.
- `keyCode?`: `number` — Numeric key code gating whether this separator is enabled, set via `kbqTagInputSeparatorKeyCodes`.
  Omit together with `key` for separators that should always be active regardless of that input.
- `appliesTo?`: `KbqTagSeparatorContext[]` — Contexts this separator applies to. Defaults to `['input', 'paste']`.

#### KbqTagSeparatorContext (type)

Contexts a `KbqTagSeparator` can be active in.

```ts
type KbqTagSeparatorContext = 'input' | 'paste';
```

### Constants

#### KBQ_TAGS_DEFAULT_OPTIONS (const)

Injection token to be used to override the default options.

```ts
const KBQ_TAGS_DEFAULT_OPTIONS: InjectionToken<KbqTagsDefaultOptions>;
```

#### kbqTagsDefaultOptionsProvider (const)

Utility provider for `KBQ_TAGS_DEFAULT_OPTIONS`.

```ts
const kbqTagsDefaultOptionsProvider: (
    options: Partial<KbqTagsDefaultOptions>
) => Provider;
```

## Examples

### Disable tag creation on the "paste" event

**Example: Tag input onpaste off** (`tag-input-onpaste-off`)

```ts tag-input-onpaste-off-example.ts
﻿import { ChangeDetectionStrategy, Component, ElementRef, viewChild } from '@angular/core';
import { FormControl, ReactiveFormsModule } from '@angular/forms';
import { COMMA, ENTER } from '@koobiq/components/core';
import { KbqFormFieldModule } from '@koobiq/components/form-field';
import { KbqIconModule } from '@koobiq/components/icon';
import { KbqTagInput, KbqTagInputEvent, KbqTagsModule, kbqTagsDefaultOptionsProvider } from '@koobiq/components/tags';

@Component({
    selector: 'tag-input-onpaste-off-example',
    imports: [
        KbqTagsModule,
        ReactiveFormsModule,
        KbqIconModule,
        KbqFormFieldModule
    ],
    templateUrl: 'tag-input-onpaste-off-example.html',
    // turn off tag add on paste with InjectionToken
    providers: [kbqTagsDefaultOptionsProvider({ separatorKeyCodes: [ENTER], addOnPaste: false })],
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class TagInputOnpasteOffExample {
    private readonly input = viewChild.required(KbqTagInput, { read: ElementRef });

    control = new FormControl();

    tags = ['tag', 'tag1', 'tag2', 'tag3', 'tag4'];

    readonly separatorKeysCodes: number[] = [ENTER, COMMA];

    onCreate(event: KbqTagInputEvent): void {
        const input = event.input;
        const value = event.value;

        if ((value || '').trim()) {
            this.tags.push(value.trim());
        }

        if (input) {
            input.value = '';
        }
    }

    onRemoveTag(tag: string): void {
        const index = this.tags.indexOf(tag);

        if (index >= 0) {
            this.tags.splice(index, 1);
        }
    }

    protected afterRemove(): void {
        this.input().nativeElement.focus();
    }
}
```

```html tag-input-onpaste-off-example.html
<kbq-form-field>
    <kbq-tag-list #tagList="kbqTagList">
        @for (tag of tags; track $index) {
            <kbq-tag [value]="tag" (removed)="onRemoveTag(tag)">
                {{ tag }}
                <i kbq-icon="kbq-xmark-s_16" kbqTagRemove (click)="afterRemove()"></i>
            </kbq-tag>
        }

        <!-- turn off tag add on paste with Input property -->
        <input
            autocomplete="off"
            placeholder="New tag"
            [formControl]="control"
            [kbqTagInputAddOnPaste]="false"
            [kbqTagInputFor]="tagList"
            [kbqTagInputSeparatorKeyCodes]="separatorKeysCodes"
            (kbqTagInputTokenEnd)="onCreate($event)"
        />
        <kbq-cleaner />
    </kbq-tag-list>
</kbq-form-field>
```
