npm package: @talrace/ngx-noder
Description: Rich Text Editor for Angular with basic WORD features and ability to create and use your own custom components. The package also provides customizable toolbar, header, custom search in editor and basic interfaces of custom components which you can overwri
Latest version: 19.0.66

# NgxNoder

## Description

Rich Text Editor for Angular with basic WORD features and ability to create and use your own custom components. The package also provides customizable toolbar, header, custom search in editor and basic interfaces of custom components which you can overwrite to suit your needs in your application.
Current version fist 2 element verion angular

#### You can get information about the API and more NgxNoder examples from the [documentation].

## Installation

Run this command to add ngx-noder package to your project

```console
npm i @talrace/ngx-noder
```

### Translation

NgxNoder uses @ngx-translate for its translations. Its should be included to list of static application assets and application should import TranslateModule. NgxNoder translates are loaded by NoderTranslateLoader.

angular.json

```typescript
"assets": [
    ...
    { "glob": "**/*", "input": "node_modules/@talrace/ngx-noder/assets", "output": "assets" }
],
```

app.module.ts

```typescript
import { TranslateModule } from '@ngx-translate/core';

@NgModule({
    imports: [
        ...
        TranslateModule.forRoot()
    ],
    ...
})
```

NgxNoder translates loading

app.module.ts (if application do not have own translations, preferred language can be set by the 'use' method of TranslateService)

```typescript
import { NoderTranslateLoader } from '@talrace/ngx-noder';
import { TranslateLoader, TranslateModule } from '@ngx-translate/core';

@NgModule({
    imports: [
        ...
        TranslateModule.forRoot({ loader: { provide: TranslateLoader, useClass: NoderTranslateLoader } })
    ],
    ...
})
```

service or state where translation is controlled (if application have own translations)

```typescript
import { NoderTranslateLoader } from '@talrace/ngx-noder';
import { TranslateService } from '@ngx-translate/core';
...
constructor(private translateService: TranslateService, private noderTranslateLoader: NoderTranslateLoader) {}
...
this.noderTranslateLoader
    .getTranslation(language)
    .pipe(take(1))
    .subscribe(x => this.translateService.setTranslation(language, x, true))
```

### Editor

Import editor module. This is basic module and provides creating, editing and viewing document functionality.

```typescript
import { EditorModule } from '@talrace/ngx-noder';

@NgModule({
    ...
    imports: [
        EditorModule.forRoot({
            elementService: ElementApiService,
            imageApiService: ImageUploadService,
            sidenav: { autoFocus: true }
        }),
     ],
    ...
})
export class SomeModule{}
```

### Editor Toolbar

Import editor toolbar module, if you need toolbar for your editor. This module provides ready-made toolbar with buttons that covers all basic logic of the document content editing functionality.

```typescript
import { EditorToolbarModule } from '@talrace/ngx-noder';

@NgModule({
    // ...
    imports: [EditorToolbarModule]
    // ...
})
export class SomeModule {}
```

### Editor Title

Import standalone editor title components to display and edit the document title line and to change the document editing mode (editing, filling, viewing).

```typescript
import { EditorTitleComponent, EditorTitleMobileComponent } from '@talrace/ngx-noder';
@NgModule({
    // ...
    imports: [EditorTitleComponent, EditorTitleMobileComponent]
    // ...
})
export class SomeModule {}
```

### Editor Search

Import standalone editor search component, if you need custom search in your editor. This component provides custom search component and search and replace functionality in editor.

```typescript
import { EditorSearchDialogComponent } from '@talrace/ngx-noder';

@NgModule({
    // ...
    imports: [EditorSearchDialogComponent]
    // ...
})
export class SomeModule {}
```

### Editor Service

Provide Editor Service in your component with editor if you need to send commands to editor or gets some document status data. This service provides functionality of send data or commands to the editor and receive document state data or document interaction mode

```typescript
import { EditorService } from '@talrace/ngx-noder';

@NgModule({
    // ...
    provides: [EditorService]
    // ...
})
export class SomeModule {}
```

## Usage

Example of full-featured NgxNoder with toolbar, header, custom search and receiving commands from editor.

angular.json

```typescript
"assets": [
    ...
    { "glob": "**/*", "input": "node_modules/@talrace/ngx-noder/assets", "output": "assets" }
],
```

app.module.ts

```typescript
import { AppComponent } from './app.component';
import {
    EditorModule,
    EditorSearchDialogComponent,
    EditorSearchDialogComponent,
    EditorTitleComponent,
    EditorTitleMobileComponent,
    EditorToolbarModule
} from '@talrace/ngx-noder';
import { NgModule } from '@angular/core';
import { NoderTranslateLoader } from '@talrace/ngx-noder';
import { TranslateLoader, TranslateModule } from '@ngx-translate/core';

@NgModule({
    declarations: [AppComponent],
    imports: [
        …
        EditorModule.forRoot({
            elementService: ElementApiService,
            imageApiService: ImageUploadService,
            sidenav: { autoFocus: true }
        }),
        EditorSearchDialogComponent,
        EditorTitleComponent,
        EditorTitleMobileComponent,
        EditorToolbarModule,
        TranslateModule.forRoot({ loader: { provide: TranslateLoader, useClass: NoderTranslateLoader } })
        …
    ],
    providers: [EditorService, ElementApiService, ImageUploadService],
    bootstrap: [AppComponent]
})

export class AppModule{}
```

app.component.html

```html
<div class="”header”">
    <app-nod-editor-mobile-toolbar
        *ngIf="isMobile; else desktopToolbar"
        (openFileFromDisk)="fileInput.click()"
        (addCustomElement)="addCustomElement($event)"
        (insertPageBreak)="onInsertPageBreak()"
        (createDocument)="createDocument()"
        (saveAs)="onSave()"
        (print)="onPrint()"
        (delete)="onDelete()"
        (rename)="rename$.next()"
        (undo)="onUndo()"
        (redo)="onRedo()"
        (insertImage)="imageFileInput.click()"
        (insertLink)="onInsertLink()"
        (insertTable)="onInsertTableMobile()"
        (createElement)="createElement($event)"
        (changeParagraphStyle)="onSetParagraphStyle($event)"
        (changeTextStyle)="onSetTextStyle($event)"
        (textFormat)="onTextFormatMobile()" />
    <ng-template #desktopToolbar>
        <app-nod-editor-toolbar
            (openFileFromDisk)="fileInput.click()"
            (addCustomElement)="addCustomElement($event)"
            (insertPageBreak)="onInsertPageBreak()"
            (createDocument)="createDocument()"
            (saveAs)="onSave()"
            (print)="onPrint()"
            (delete)="onDelete()"
            (rename)="rename$.next()"
            (undo)="onUndo()"
            (redo)="onRedo()"
            (openEditMenu)="onOpenEditMenu()"
            (cutSelected)="onCutSelected()"
            (copySelected)="onCopySelected()"
            (pasteClipboardData)="onPasteClipboardData()"
            (selectAll)="onSelectAll()"
            (removeSelected)="onRemoveSelected()"
            (insertImage)="imageFileInput.click()"
            (insertLink)="onInsertLink()"
            (insertTable)="onInsertTable($event)"
            (createElement)="createElement($event)"
            (changeParagraphStyle)="onSetParagraphStyle($event)"
            (changeTextStyle)="onSetTextStyle($event)"
            (setNumberingTemplateType)="onSetNumberingTemplateType($event)"
            (removeNumberings)="onRemoveNumberings()" />
    </ng-template>
</div>
<app-nod-editor
    #editor
    [isMobile]="isMobile"
    [customPageWidth]="customPageWidth"
    [content]="content$ | async" />
<ng-container *ngIf="{ mode: mode$ | async } as modeData">
    <ng-container *ngIf="isMobile; else desktopTitle">
        <app-nod-editor-title-mobile
            *ngIf="showTitleModes.includes(editorToolbarService.mode$ | async)"
            [selectedMode]="modeData.mode"
            [title]="title"
            [rename$]="rename$.asObservable()"
            (changeMode)="onModeChanged($event)"
            (renameDocumentTitle)="onRenameDocumentTitle($event)" />
    </ng-container>
    <ng-template #desktopTitle>
        <app-nod-editor-title
            [selectedMode]="modeData.mode"
            [title]="title"
            [rename$]="rename$.asObservable()"
            (changeMode)="onModeChanged($event)"
            (renameDocumentTitle)="onRenameDocumentTitle($event)" />
    </ng-template>
</ng-container>
<input
    #fileInput
    class="upload-input"
    accept=".docx"
    type="file"
    id="file-input"
    (change)="onConvertFile($event)" />
<input
    #imageFileInput
    class="upload-input"
    accept="image/gif, image/jpeg, image/png, image/bmp, image/webp"
    type="file"
    id="image-file-input"
    (change)="onInsertImage($event)" />
```

app.component.ts

```typescript
import { Actions, ofActionDispatched, Store } from '@ngxs/store';
import { ActivatedRoute } from '@angular/router';
import { BehaviorSubject, filter, Observable, Subject, take, takeUntil, tap } from 'rxjs';
import {
    AddLinkDialogComponent,
    AddLinkMobileComponent,
    BreakTypes,
    CommandsService,
    DestroyComponent,
    DocxModel,
    EditorComponent,
    EditorSearchDialogComponent,
    EditorService,
    EditorToolbarMode,
    EditorToolbarService,
    ElementDataModel,
    Mode,
    NumberingLevelModel,
    ParagraphStyleModel,
    RevisionHelper,
    TextFormatMobileComponent,
    TextStyleModel
} from '@talrace/ngx-noder';
import { Component, ElementRef, ViewChild } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { Navigate } from '@ngxs/router-plugin';

import { ClearRevision, ConvertFile, OpenDocx, RenameDocument, SaveDocument, SetMode } from '../../store/noder/noder.actions';
import { CreateOperation } from '../../store/operations/operations.actions';
import { DeleteDocuments } from '../../../documents/store/documents/documents.actions';
import { FileSaveDialogComponent } from '../file-save/file-save-dialog.component';
import { ImageUploadService } from '../../services/image-upload.service';
import { LayoutState } from '../../../+shared/layout/store/layout.state';
import { NoderState } from '../../store/noder/noder.state';

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.scss']
})
export class AppComponent extends DestroyComponent {
    mode$ = this.store.select(NoderState.mode);
    rename$ = new Subject<void>();
    title: string;
    documentId: number;
    isMobile = false;
    get content$(): Observable<DocxModel> {
        return this._content$.asObservable();
    }
    private _content$ = new BehaviorSubject<DocxModel>(RevisionHelper.getEmptyDocxModel());
    @ViewChild('editor', { static: true }) editor: EditorComponent;
    @ViewChild('fileInput', { static: true }) fileInput: ElementRef<HTMLInputElement>;
    readonly customPageWidth = this.store.selectSnapshot(LayoutState.isMobile) ? window.innerWidth : null;
    readonly showTitleModes = [
        EditorToolbarMode.Base,
        EditorToolbarMode.TextFormat,
        EditorToolbarMode.StyleFormat,
        EditorToolbarMode.AlignFormat
    ];

    constructor(
        private actions$: Actions,
        private commandService: CommandsService,
        private dialog: MatDialog,
        private editorService: EditorService,
        private imageUploadService: ImageUploadService,
        private route: ActivatedRoute,
        private store: Store,
        public editorToolbarService: EditorToolbarService
    ) {
        super();
        const mode: Mode = this.store.selectSnapshot(NoderState.mode);
        this.editorService.setIsViewOnly(mode !== Mode.Edit);
    }

    ngOnInit() {
        this.isMobileSubscription();
        this.openCloseSearchSubscription();
        this.routeDataSubscription();
        this.documentTitleSubscription();
        this.documentIdSubscription();
        this.createCommandSubscription();
        this.editorHotKeyDownSubscription();
    }

    createDocument(): void {
        const documentId = +this.route.snapshot.params['id'];
        if (documentId) {
            this.store.dispatch([new ClearRevision(), new Navigate([''])]);
        } else {
            this.store.dispatch(new ClearRevision());
            this._content$.next(RevisionHelper.getEmptyDocxModel());
        }
    }

    onConvertFile(event: any): void {
        if (!event?.target?.files?.length) {
            return;
        }
        let file: File = event.target.files[0];
        if (!file.type.match('application/vnd.openxmlformats-officedocument.wordprocessingml.document')) {
            return;
        }
        this.store.dispatch(new ConvertFile(file as Blob));
        this.actions$
            .pipe(ofActionDispatched(OpenDocx), take(1))
            .subscribe(payload => this.store.dispatch(new Navigate([`noder/${payload.documentId}`])));
        event.target.value = null;
    }

    onSave(): void {
        const dialogRef = this.dialog.open(FileSaveDialogComponent, {
            panelClass: 'file-save-dialog',
            height: '230px',
            width: '350px',
            data: { documentName: '' }
        });
        dialogRef.afterClosed().subscribe((name: string) => {
            if (!name?.length) {
                return;
            }
            this.store.dispatch(new SaveDocument(name, this.editor.content));
        });
    }

    onPrint(): void {
        this.editorService.print();
    }

    onDelete(): void {
        const documentId = this.store.selectSnapshot(NoderState.documentId);
        this.dialog
            .open<ConfirmDialogComponent>(ConfirmDialogComponent, {
                autoFocus: false,
                restoreFocus: false,
                data: <IDialogData>{ message: 'Are you sure you want to delete?' }
            })
            .afterClosed()
            .pipe(filter(x => !!x))
            .subscribe(() => {
                const actions: any = [new Navigate(['noder', 'new'])];
                if (documentId) {
                    actions.unshift(new DeleteDocuments([documentId]));
                }
                this.store.dispatch(actions);
            });
    }

    onInsertPageBreak(): void {
        this.editorService.insertBreak(BreakTypes.Page);
    }

    async onInsertImage(event: any): Promise<void> {
        if (!event?.target?.files?.length) {
            return;
        }
        const file = event.target.files[0];
        if (!'image/gif, image/jpeg, image/png, image/bmp, image/webp'.match(file.type as string)) {
            return;
        }
        const model = await this.imageUploadService.uploadImage(file as Blob);
        this.editorService.insertImage(model);
        event.target.value = null;
    }

    onInsertTable(model: { rows: number; columns: number }): void {
        this.editorService.insertTable(model);
    }

    onInsertTableMobile(): void {
        this.editorService.openSidenav(InsertTableMobileComponent);
    }

    onSetTextStyle(value: TextStyleModel): void {
        this.editorService.setTextStyles(value);
    }

    onSetNumberingTemplateType(value: NumberingLevelModel[]): void {
        this.editorService.setNumberingTemplateType(value);
    }

    onRemoveNumberings(): void {
        this.editorService.removeNumberings();
    }

    onInsertLink(): void {
        if (this.isMobile) {
            this.editorService.openSidenav(AddLinkMobileComponent);
        } else {
            this.dialog
                .open(AddLinkDialogComponent, { panelClass: 'add-link-dialog' })
                .afterClosed()
                .subscribe((result: any) => {
                    if (result) {
                        this.editorService.insertLink(result.text as string, result.link as string);
                    }
                });
        }
    }

    addCustomElement(model: ElementDataModel): void {
        this.editorService.createCustomComponent(model);
    }

    onSetParagraphStyle(value: ParagraphStyleModel): void {
        this.editorService.setParagraphStyles(value);
    }

    onModeChanged(value: Mode): void {
        this.store.dispatch(new SetMode(value));
        this.editorService.setIsViewOnly(value !== Mode.Edit);
    }

    onUndo(): void {
        this.editorService.undo();
    }

    onRedo(): void {
        this.editorService.redo();
    }

    async onOpenEditMenu(): Promise<void> {
        const read = await navigator.permissions.query({ name: 'clipboard-read' as PermissionName });
        if (read.state != 'denied' && navigator.clipboard) {
            navigator.clipboard
                .readText()
                .then(value => {
                    return this.editorService.setClipboardData(value);
                })
                .catch(() => {
                    // continue regardless error
                });
        }
    }

    onCutSelected(): void {
        this.editorService.cutSelected();
    }

    onCopySelected(): void {
        this.editorService.copySelected();
    }

    onPasteClipboardData(): void {
        this.editorService.pasteFromClipboard();
    }

    onSelectAll(): void {
        this.editorService.selectAll();
    }

    onRemoveSelected(): void {
        this.editorService.removeSelected();
    }

    onRenameDocumentTitle(title: string): void {
        this.store.dispatch(new RenameDocument(new DocumentNameModel({ documentId: this.documentId, name: title })));
    }

    createElement(model: ElementDataModel) {
        this.editor.editor.createCustomElement(model);
        this.editor.editor.focus();
    }

    onTextFormatMobile(): void {
        this.editorService.openSidenav(TextFormatMobileComponent);
    }

    onEditorHotKeyDown(event: KeyboardEvent): void {
        if (event.ctrlKey && event.code === 'KeyO') {
            this.fileInput.nativeElement.click();
        } else if (event.ctrlKey && event.code === 'KeyK') {
            this.onInsertLink();
        } else {
            return;
        }
        event.preventDefault();
    }

    private onOpenSearch(): void {
        this.dialog.open(EditorSearchDialogComponent, {
            position: { top: '0px', right: '0px' },
            hasBackdrop: false
        });
    }

    private isMobileSubscription(): void {
        this.store
            .select(LayoutState.isMobile)
            .pipe(takeUntil(this.destroy$))
            .subscribe(x => (this.isMobile = x));
    }

    private openCloseSearchSubscription(): void {
        this.editorService.openSearchDialog$.pipe(takeUntil(this.destroy$)).subscribe(value => {
            value ? this.onOpenSearch() : this.dialog.closeAll();
        });
    }

    private routeDataSubscription(): void {
        this.route.data.pipe(takeUntil(this.destroy$)).subscribe(({ content }) => this._content$.next(content as DocxModel));
    }

    private documentTitleSubscription(): void {
        this.store
            .select(NoderState.title)
            .pipe(takeUntil(this.destroy$))
            .subscribe(x => (this.title = x ?? 'Untitled document'));
    }

    private documentIdSubscription(): void {
        this.store
            .select(NoderState.documentId)
            .pipe(takeUntil(this.destroy$))
            .subscribe(x => (this.documentId = x));
    }

    private createCommandSubscription(): void {
        this.commandService.createCommand$
            .pipe(
                filter(x => !!x),
                tap(command => {
                    this.store.dispatch(new CreateOperation(command));
                }),
                takeUntil(this.destroy$)
            )
            .subscribe();
    }

    private editorHotKeyDownSubscription(): void {
        this.editorService.keyDown$.pipe(takeUntil(this.destroy$)).subscribe(event => this.onEditorHotKeyDown(event));
    }
}
```

app.component.scss

```scss
// styles of your app component
:host {
    height: inherit;
    width: 100%;
    display: flex;
    flex-direction: column;
    overflow: hidden;
}
```

[documentation]: https://npmjs.talrace.com/text/ngx-noder