@3kles/kles-richtext-editor
v1.4.1
Published
Use `items`, `config`, and `buttonTemplate` to choose, order, hide, disable, and customize toolbar controls. Use `refreshKey` or `refresh()` when command availability depends on state outside the editor. The toolbar, editor, and preview accept `locale` an
Keywords
Readme
Angular rich text editor
Use items, config, and buttonTemplate to choose, order, hide, disable, and customize toolbar controls. Use refreshKey or refresh() when command availability depends on state outside the editor. The toolbar, editor, and preview accept locale and messages. The provideRichTextToolbar and provideRichTextI18n providers set defaults for an injection scope. The shipped catalogs support English and French, including accessible names. The default toolbar uses the built-in controls and the French catalog. Try the demo at /?view=toolbar. Configuration and examples · Performance results
@3kles/kles-richtext-editor follows the Angular Package Format and the 3KLES src/lib and src/public-api.ts layout. It exposes three standalone OnPush components, RichTextEditorComponent (kles-richtext-editor), RichTextToolbarComponent (kles-richtext-toolbar), and RichTextDocumentPreviewComponent, a read-only JSON preview.
Toolbar icons
Use { id: 'undo', icon: 'undo' } for an icon-only Undo button. The undo and redo icon names use Material Icons by default. For other Material ligatures, set iconType: 'material', for example { id: 'bold', icon: 'format_bold', iconType: 'material' }. Use iconType: 'text' to display a literal string.
Set label: '' on a built-in button with an icon to hide its visible text explicitly. The button keeps its translated accessible name and tooltip. Set a nonempty label or labelKey to show text beside a Material icon.
Set iconOnly: true in provideRichTextToolbar() or [config] to hide the visible text of every configured button that has an icon, including custom commands with a translated label. In this mode the link field uses Material icons for Apply and Remove. The URL field keeps its visible label. Tooltips and accessible names use the active i18n catalog and its overrides.
The host loads the Material Icons font. The Dynamic Forms demo serves it locally. Set --kles-richtext-toolbar-material-icon-font to the name of a compatible icon font already loaded by your application. Material Icons setup
Angular Forms
The editor implements ControlValueAccessor and Validator. It works with [formControl], formControlName, and ngModel when the host imports the corresponding Forms module.
import { Component } from '@angular/core';
import { FormControl, ReactiveFormsModule } from '@angular/forms';
import { RichTextEditorComponent, RichTextToolbarComponent } from '@3kles/kles-richtext-editor';
import type { DocumentNode } from '@3kles/richtext-core';
@Component({
selector: 'document-form',
standalone: true,
imports: [ReactiveFormsModule, RichTextEditorComponent, RichTextToolbarComponent],
template: `
<kles-richtext-editor
#editor
[formControl]="control"
[required]="true"
[invalid]="control.invalid && (control.touched || control.dirty)"
label="Document"
/>
<kles-richtext-toolbar [editor]="editor" />
`,
})
export class DocumentFormComponent {
readonly control = new FormControl<DocumentNode | null>(null, { updateOn: 'blur' });
}The default form value is the native DocumentNode AST. Passing null, including through reset(), displays a canonical empty document. The core validates and copies external values. If a value is invalid, the editor keeps displaying the previous document and reports richtextDocument with schema diagnostics. Select formValueFormat="html" when binding a control containing HTML strings.
An external write received during a native notification takes precedence over the remaining events from that edit. If the write is invalid, the editor preserves its error and the control value until notification completes. The earlier documentChange cannot overwrite it through onChange. A newer valid write supersedes the rejected write, and a subsequent edit can correct the invalid value.
Forms owns the value as soon as it calls writeValue or registers its change callback. The editor then ignores updates to the legacy [document] input. Load form values through control.setValue(document), patchValue, or reset.
The CVA onChange callback receives actual document edits from input, commands, paste, undo, and redo. External writes, loads, selection changes, and access changes preserve the control's pristine or dirty state. Angular manages pristine/dirty, touched/untouched, updateOn, reset, and the exclusion of disabled controls from form.value.
Inputs, signals, and outputs
| Contract | Behavior |
| ------------------------ | ---------------------------------------------------------------------------------------------------- |
| document: DocumentNode | Legacy input for use outside Forms. Loading it does not emit documentChange. |
| readOnly: boolean | Blocks editing and allows focus, selection, and copying. |
| disabled: boolean | Disables the surface and removes it from tab navigation if this input or Forms disables the control. |
| required: boolean | Requires nonempty document text after trimming whitespace. |
| invalid: boolean | Optional visual state from the host. Control validators operate independently. |
| label: string | Accessible name of the surface. |
| describedBy: string | Consumer-owned instruction IDs to include alongside internal error descriptions. |
| documentChange | Canonical document after an edit, as in the original contract. |
| stateChange | Current native state, including selection and metadata. |
| editorEvent | Typed native events, including content diagnostics. |
| validationChange | Schema or required-content errors in the view. |
The four boolean inputs accept boolean bindings or HTML attributes through booleanAttribute. Use the public signals state(), composing(), focused(), effectiveDisabled(), editable(), and validationError() to observe state without accessing the native instance. state() is undefined before mounting and after destruction. The surface exposes its name, access, required status, and validation state through ARIA attributes. Pass external Forms status through [invalid] to avoid circular NgControl injection.
The legacy input and output bindings also work outside Forms.
<kles-richtext-editor
[document]="document()"
[readOnly]="readOnly()"
(documentChange)="document.set($event)"
label="Document content"
/>Validation
The NG_VALIDATORS provider always applies the native schema. required also checks for text in paragraphs, headings, lists, blockquotes, and code blocks. Empty paragraphs, line breaks alone, and whitespace-only text count as empty. Use the rich-text validator to enforce this rule, since Validators.required alone treats any AST object as present.
You can use richTextDocumentValidator(control) and richTextRequiredValidator(control) as explicit validators. validateRichTextValue(value) returns a typed validation result and interprets null as an empty document. Errors have the shape { richtextDocument: { diagnostics } } or { required: true }. Invalid values produce schema errors.
Validation runs immediately. A pristine control displays its required error after an edit, a move outside the shared focus region, or submission. The editor reports schema errors in external values immediately. Each displayed error has a visible message associated through aria-describedby. [invalid] can display an error from the host's business rules. describedBy="document-help" includes host instructions alongside the error message. writeValue resets presentation tied to the previous interaction. Internal IDs are scoped to the Angular application. Set distinct APP_ID values when several applications share the page. Accessibility checks and limits
Focus, touched state, and composition
The surface and toolbar controls share a focus region. onTouched fires when focus leaves that region after an interaction. Moving from the surface to a button, the heading selector, or the link field stays inside it. A custom toolbar can join the region with registerFocusRegion(element), which returns a cleanup function. Programmatic focus alone, value writes, and disabling the surface preserve the control's touched state.
An IME uses native pre-edit text within a block. If focus leaves during composition, processing waits for the session to resolve. The editor sends the final document to onChange before onTouched, so updateOn: 'blur' receives the final value. The editor defers external writes during composition and applies the last valid one when the session ends. A pending external write suppresses intermediate composition updates to Forms and documentChange to protect the write. An invalid external value cancels the previous deferred write and any pre-edit started before it. The last valid AST stays visible, the schema error stays present, and onChange leaves the rejected external value intact. If the engine is publishing events, cancellation runs in the next microtask. New input can then correct the control value.
With updateOn: 'submit', the component listens for submission on the ancestor form during capture. If compositionend has already arrived, it finishes the composition synchronously before Angular processes the form. This lets a requestSubmit() in the same turn receive the confirmed document. If the pre-edit is unconfirmed or a native notification prevents resolution, the component calls preventDefault and stopImmediatePropagation to stop submission without publishing pre-edit text. Submit again after composition or the current notification finishes. The listener is browser-only and is removed on destruction.
The component defers readOnly until composition ends. disabled immediately blocks the surface and cancels the pre-edit session in the model without committing it. When a native notification is in progress, metadata updates run in the next microtask. This behavior applies to the editor model, while the operating system manages its IME panel. The loaded document remains available in read-only mode. A disabled control follows standard Angular Forms rules.
Commands and conversions
execute(command) returns a typed action result. It returns undefined before mounting, after destruction, or while the component is disabled. The focus(), getDocument(), canUndo(), canRedo(), isActive(mark), can(command), and isActiveCommand(command) methods support custom toolbars. The built-in toolbar uses those capabilities and preserves the canonical selection during link editing. Command contracts
loadHtml(html, emitChange = false), insertHtml(html), and getHtml() expose sanitized conversion and diagnostics. Loading replaces the document, resets history, and works in read-only mode. The legacy emitChange option requests a documentChange output without calling the Forms onChange callback. Insertion is an undoable edit. editorEvent also reports paste diagnostics as contentDiagnostics. To load HTML into a form, convert it to an AST and write that value to the control.
The toolbar and setLink accept complete template destinations such as ${context.url}. The editor and preview keep these destinations inert. loadHtml() and getHtml() preserve the literal variable in href, ready for the consuming application's template rendering.
Configuration and lifecycle
RICHTEXT_EDITOR_EXTENSIONS configures instances within its injection scope. Without a provider, the editor installs the native preset. An empty array preserves basic editing and existing documents. The editor captures the configuration at mount time and rejects collisions before modifying the surface.
The component creates the native instance once after initializing the browser view. Ordinary Angular changes, form values, and access settings reuse that instance. Server rendering preserves declarative elements and attributes. Destruction releases subscriptions, focus regions, callbacks, and DOM references, and deactivates deferred writes.
The peer dependencies are @angular/common, @angular/core, and @angular/forms, all at ^22.2.6. The underlying engine is independent of Angular and zone.js. The wrapper uses the native editor engine.
The workspace Angular and browser suites verify Forms, the toolbar, and consumption from an external package. The phase reports document limits for cross-platform composition, Firefox and WebKit, screen readers, and performance.
Dynamic Forms
Import RichTextDynamicFieldComponent and RichTextDynamicFieldConfig from @3kles/kles-richtext-editor/dynamicforms. This entry point requires the optional peer @3kles/kles-material-dynamicforms at ^22.11.0. The primary entry point works independently of that peer.
import { provideRichTextToolbar, richTextHtmlRequiredValidator } from '@3kles/kles-richtext-editor';
import { RichTextDynamicFieldComponent } from '@3kles/kles-richtext-editor/dynamicforms';
import type { RichTextDynamicFieldConfig } from '@3kles/kles-richtext-editor/dynamicforms';
const body: RichTextDynamicFieldConfig = {
name: 'body',
component: RichTextDynamicFieldComponent,
label: 'Message',
richTextValueFormat: 'html',
value: '<p><a href="${process.url}">Open the process</a></p>',
providers: [provideRichTextToolbar({ items: ['bold', 'italic', 'link', 'undo', 'redo'] })],
validations: [{ name: 'required', message: 'Enter a message.', validator: richTextHtmlRequiredValidator }],
};Omit richTextValueFormat for the default DocumentNode | null control. HTML mode uses string | null. An external HTML value is imported into the editor without rewriting the control. Edits write sanitized HTML with the original template destinations in href. The empty paragraph exports as '' after an edit, and reset(null) retains null. Template destinations remain inert in the editing DOM. The host resolves them when generating the final document.
For Angular Forms outside Dynamic Forms, use formValueFormat="html" on kles-richtext-editor with a FormControl<string | null>. The document input, documentChange output and native editor APIs still use the AST. Configure the value format when creating the control. Dynamic Forms demo
