# docx-editor-mail-merge

> Document editor sample demonstrating mail merge fields and generated recipient documents.

**Framework:** angular  **Component:** DocxEditor  **Variant:** mail-merge

## Get this item

**If you are an agent, fetch the JSON.** Source is inlined, so one request is enough and no tooling is required:

```
GET https://ai.syncfusion.com/r/angular/docx-editor-mail-merge.json
```

**Install Package(s)**

```bash
npm install @syncfusion/ej2-angular-documenteditor @syncfusion/ej2-angular-lists @syncfusion/ej2-lists @syncfusion/ej2-navigations @syncfusion/ej2-popups
```

**Notes**

- Syncfusion release: 2026 Volume 3 (v35.1.37)
- The Syncfusion package is licensed. The composition in this file is source you own and edit. See https://ai.syncfusion.com/licensing.md

## Source files

### src/components/docx-editor-mail-merge/docx-editor.component.html

```html
<div class="control-section">
    <div>
       <div id='default_title_bar' class="e-de-ctn-title"></div>
    <div class="col-lg-2 property-section" style="padding-right: inherit;padding-left: 5px;height: 600px;border-left: 1px solid rgb(238, 238, 238);border-bottom:  1px solid rgb(238, 238, 238) ;"> 
        <h5><label style="display:block;margin:1px;padding-top: 5px">Select Field to Insert</label></h5>
        <div >
          <ejs-listview id='listview' [dataSource]='listData' (select)="onSelect($event)" allowDragAndDrop='true' [fields]="fields"></ejs-listview>
        </div></div>
    
       
        <div class="col-lg-10 control-section"  style='padding-left: 0px;padding-right: 0px; padding-top: 0px;' >
          <div>
            <ejs-documenteditorcontainer #documenteditor_default id="container" [enableToolbar]=true [locale]="culture" (created)="onCreate()"  (documentChange)="onDocumentChange()" (toolbarClick)="toolbarClick($event)" [serviceUrl]="hostUrl"  height="600px" style="display:block" ></ejs-documenteditorcontainer>
          </div>
        </div>
          <div class="overlay" id="popup-overlay" style="display: none;"></div>
    <div id='waiting-popup' style="display: none;">
        <svg class="circular" height="40" width="40">
            <circle class="circle-path" cx="25" cy="25" r="20" fill="none" stroke-width="6" stroke-miterlimit="10" />
        </svg>
    </div>
        
    </div>
</div>

<style>
    @import '../style.css';
    .overlay {
      position: fixed;
      top: 0;
      left: 0;
      width: 100vw;
      height: 100vh;
      background-color: rgba(56, 56, 56, 0.5);
      z-index: 9999;
      display: none;
      cursor: not-allowed;
    }

    #waiting-popup {
      width: 56px;
      height: 56px;
      position: fixed;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      border-radius: 50%;
      padding: 3px;
      background: white;
      box-shadow: 0px 3px 6px rgba(0,0,0,.3);
      z-index: 10000;
      display: none;
    }

    .circular {
        animation: rotate 2s linear infinite;
        height: 50px;
        width: 50px;
        border-radius: 50%;
    }

    .circle-path {
        stroke-dasharray: 1, 200;
        stroke-dashoffset: 0;
        animation: dash 1.5s ease-in-out infinite, color 6s ease-in-out infinite;
        stroke-linecap: round;
        stroke: #ff4081;
    }

    @keyframes rotate {
        100% {
            transform: rotate(360deg);
        }
    }

    @keyframes dash {
        0% {
            stroke-dasharray: 1, 200;
            stroke-dashoffset: 0;
        }

        50% {
            stroke-dasharray: 89, 200;
            stroke-dashoffset: -35;
        }

        100% {
            stroke-dasharray: 89, 200;
            stroke-dashoffset: -124;
        }
    }

    #documenteditor_title_contentEditor {
        height: 26px;
        max-width: 75%;
        width: auto;
        overflow: hidden;
        display: inline-block;
        padding-left: 4px;
        padding-right: 4px;
        margin: 5px;
    }

    .single-line {
        cursor: text !important;
        outline: none;
    }

    #default_title_bar {
        height: 36px;
        line-height: 26px;
        width: 100%;
        font-size: 12px;
        padding-left: 15px;
        padding-right: 10px;
        font-family: inherit;
		box-sizing: border-box;
    }

    [class^="e-de-icon-"],
    [class*=" e-de-icon-"] {
        font-family: 'Sample brower icons' !important;
    }

    .e-de-icon-Print:before {
        content: "\e723";
    }

    .e-de-icon-Download:before {
        content: "\e728";
    }

[class^="sf-icon-"], [class*=" sf-icon-"] {
 font-family: 'Font Mail merge icon' !important;
 color: rgba(0, 0, 0, 0.54);
 font-weight: 600;
 font-size: 14px;
}
    .sf-icon-FinishMerge:before { content: "\e700"; }
.sf-icon-InsertMergeField:before { content: "\e701"; }

    /** sample level font icons ends*/
</style>
<script>
    window.onbeforeunload = function () {
        return 'Want to save your changes?';
    };    
</script>
```

### src/components/docx-editor-mail-merge/docx-editor.component.ts

```typescript
import { Component, ViewEncapsulation, ViewChild,  OnInit } from '@angular/core';
import { ToolbarService, DocumentEditorContainerComponent, DocumentEditorContainerModule } from '@syncfusion/ej2-angular-documenteditor';
import { TitleBar } from '../title-bar';
import { ClickEventArgs } from '@syncfusion/ej2-navigations/src/toolbar/toolbar';
import { mailmerge, WEB_API_ACTION, mailListData } from '../datasource/docx-editor-data';
import { ListView, SelectEventArgs } from '@syncfusion/ej2-lists';
import { isNullOrUndefined } from '@syncfusion/ej2-base';
import { Dialog, DialogUtility } from '@syncfusion/ej2-popups';
import { ListViewModule } from '@syncfusion/ej2-angular-lists';
/**
 * Document Editor Component
 */
@Component({
    selector: 'control-content',
    templateUrl: 'docx-editor.component.html',
    encapsulation: ViewEncapsulation.None,
    providers: [ToolbarService],
    standalone: true,
    imports: [ListViewModule, DocumentEditorContainerModule]
})
export class MailMergeComponent {
    public hostUrl: string = 'https://document.syncfusion.com/web-services/docx-editor/api/documenteditor/';
    @ViewChild('documenteditor_default')
    public container!: DocumentEditorContainerComponent;
    public culture: string = 'en-US';
    titleBar!: TitleBar;
    public editArea!: HTMLElement;
    public item =['New', 'Open', 'Separator', 'Undo',
            'Redo',
            'Separator',
            {
                prefixIcon: 'sf-icon-InsertMergeField',
                tooltipText: 'Insert Field',
                text: this.onWrapText('Insert Field'),
                id: 'InsertField'
            },
            {
                prefixIcon: 'sf-icon-FinishMerge',
                tooltipText: 'Merge Document',
                text: this.onWrapText('Merge Document'),
                id: 'MergeDocument'
            },
            'Separator',
            'Image',
            'Table',
            'Hyperlink',
            'Bookmark',
            'TableOfContents',
            'Separator',
            'Header',
            'Footer',
            'PageSetup',
            'PageNumber',
            'Break',
            'Separator',
            'Find',
            'Separator',
            'Comments',
            'TrackChanges',
            'Separator',
            'LocalClipboard',
            'RestrictEditing',
            'Separator',
            'FormFields',
            'UpdateFields'
            ];
     onWrapText(text: string): string {
        let content: string = '';
        let index: number = text.lastIndexOf(' ');
        content = text.slice(0, index);
        text.slice(index);
        content += '<div class="e-de-text-wrap">' + text.slice(index) + '</div>';
        return content;
    }
     

    onCreate(): void {
        let titleBarElement: HTMLElement = document.getElementById('default_title_bar')!;
        this.titleBar = new TitleBar(titleBarElement, this.container.documentEditor, true);
        this.container.documentEditor.open(JSON.stringify(mailmerge));
        this.container.documentEditor.documentName = 'Mail Merge';
        this.container.documentEditorSettings.showRuler = true;
        this.titleBar.updateDocumentTitle();
        let toolbaritems : any = this.item;
        this.container.toolbarItems = toolbaritems;
        document.getElementById("listview")!.addEventListener("dragstart", function (event) {
      event.dataTransfer!.setData("Text", (event.target as any).innerText);
      (event.target as any).classList.add('de-drag-target');

    });

    // Prevent default drag over for document editor element
    this.container.documentEditor.element.addEventListener("dragover", function (event) {
      event.preventDefault();
    });

    // Drop Event for document editor element
    this.container.documentEditor.element.addEventListener("drop", (e) => {
      var text = e.dataTransfer!.getData('Text');//.replace(/\n/g, '').replace(/\r/g, '').replace(/\r\n/g, '');
      this.container.documentEditor.selection.select({ x: e.offsetX, y: e.offsetY, extend: false });
      //this.container.documentEditor.editor.insertText(text);
      this.insertField(text);
    });

    document.addEventListener("dragend", (event) => {
      if ((event.target as any).classList.contains('de-drag-target')) {
        (event.target as any).classList.remove('de-drag-target');
      }
    });
       
    }
     toolbarClick = (args: ClickEventArgs): void => {
        switch (args.item.id) {
            case 'MergeDocument':
                this.mergeDocument();
                break;
            case 'InsertField':
                this.showInsertFielddialog();
                break;
        }
    };
     
    

    onDocumentChange(): void {
        if (!isNullOrUndefined(this.titleBar)) {
            this.titleBar.updateDocumentTitle();
        }
        this.container.documentEditor.focusIn();
    }
     mergeDocument(): void {
        this.container.documentEditor.saveAsBlob('Docx').then((blob: Blob) => {
            let exportedDocumment: Blob = blob;
            let fileReader: any = new FileReader();
            fileReader.onload = (): void => {
                let base64String: any = fileReader.result;
                let responseData: any = {
                    fileName: this.container.documentEditor.documentName + '.docx',
                    documentData: base64String
                };
               
                this.showHideWaitingIndicator(true);
                let baseUrl: string = 'https://document.syncfusion.com/web-services/docx-editor/api/documenteditor/MailMerge';
                let httpRequest: XMLHttpRequest = new XMLHttpRequest();
                httpRequest.open('POST', baseUrl, true);
                httpRequest.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');
                httpRequest.onreadystatechange = () => {
                    if (httpRequest.readyState === 4) {
                        if (httpRequest.status === 200 || httpRequest.status === 304) {
                            this.container.documentEditor.open(httpRequest.responseText);
                        } else {
                            // Failed to merge document
                            DialogUtility.alert({
                                title: 'Information',
                                content: 'failure to merge document',
                                showCloseIcon: true,
                                closeOnEscape: true,
                            });
                        }
                        this.showHideWaitingIndicator(false);
                    }
                };
                httpRequest.send(JSON.stringify((<any>responseData)));
            };
            fileReader.readAsDataURL(blob);
        });
    }
   
     showHideWaitingIndicator(show: boolean): void {
        let waitingPopUp: HTMLElement = document.getElementById('waiting-popup')!;
        let inActiveDiv:HTMLElement = document.getElementById('popup-overlay')!;
        inActiveDiv.style.display = show ? 'block' : 'none';
        waitingPopUp.style.display = show ? 'block' : 'none';
    }
    showInsertFielddialog(): void {
        let instance: any = this;
        if (document.getElementById('insert_merge_field') === null || document.getElementById('insert_merge_field') === undefined) {
            let fieldcontainer: any = document.createElement('div');
            fieldcontainer.id = 'insert_merge_field';
            document.body.appendChild(fieldcontainer);
            this.insertFieldDialogObj.appendTo('#insert_merge_field');
            fieldcontainer.parentElement.style.position = 'fixed';
            fieldcontainer.style.width = 'auto';
            fieldcontainer.style.height = 'auto';
        }
        this.insertFieldDialogObj.close = (): void => { this.container.documentEditor.focusIn(); };
        this.insertFieldDialogObj.beforeOpen = (): void => { this.container.documentEditor.focusIn(); };
        this.insertFieldDialogObj.show();
        let fieldNameTextBox: any = document.getElementById('field_text');
        fieldNameTextBox.value = '';
    }
    closeFieldDialog(): void {
        this.insertFieldDialogObj.hide();
        this.container.documentEditor.focusIn();
    }
    insertFieldDialogObj: Dialog = new Dialog({
        header: 'Merge Field',
        content:
            '<div class="dialogContent">'
            // tslint:disable-next-line:max-line-length
            + '<label class="e-insert-field-label">Name:</label></br><input type="text" id="field_text" class="e-input" placeholder="Type a field to insert eg. FirstName">'
            + '</div>',
        showCloseIcon: true,
        isModal: true,
        width: 'auto',
        height: 'auto',
        close: this.closeFieldDialog,
        buttons: [
            {
                'click': (): void => {
                    let fieldNameTextBox: any = document.getElementById('field_text');
                    let fieldName: any = fieldNameTextBox.value;
                    if (fieldName !== '') {
                        this.container.documentEditor.editor.insertField('MERGEFIELD ' + fieldName + ' \\* MERGEFORMAT');
                    }
                    this.insertFieldDialogObj.hide();
                    this.container.documentEditor.focusIn();
                },
                buttonModel: {
                    content: 'Ok',
                    cssClass: 'e-flat',
                    isPrimary: true,
                },
            },
            {
                'click': (): void => {
                    this.insertFieldDialogObj.hide();
                    this.container.documentEditor.focusIn();
                },
                buttonModel: {
                    content: 'Cancel',
                    cssClass: 'e-flat',
                },
            },
        ],
    });
    public listData: { [key: string]: Object }[] = mailListData;
    public fields:object = { tooltip:"category"};
    onSelect(args: SelectEventArgs): void {
        let fieldName: any = args.text;
        this.insertField(fieldName);
    }
     insertField(fieldName: any): void {
        let fileName: any = fieldName.replace(/\n/g, '').replace(/\r/g, '').replace(/\r\n/g, '');
        let fieldCode: any = 'MERGEFIELD  ' + fileName + '  \\* MERGEFORMAT ';
        this.container.documentEditor.editor.insertField(fieldCode, '«' + fieldName + '»');
        this.container.documentEditor.focusIn();
    }
}

```
