Methods in Angular Block Editor component
18 Nov 201824 minutes to read
The Block Editor component provides a comprehensive set of public methods to programmatically interact with and manipulate the editor content. These methods enable adding, removing, updating, and managing blocks, as well as controlling selection, formatting, and other editor operations.
Block Management Methods
Adding a block
Add a new block to the editor at a specified position using the addBlock method. This method can also insert the block before or after a target block.
// Add a new paragraph block after a specific block
public newBlock: BlockModel = {
id: 'new-block',
blockType: 'Paragraph',
content: [
{
contentType: ContentType.Text,
content: 'This is a newly added block'
}
]
};
editor.addBlock(newBlock, 'target-block-id', true); // true = after, false = beforeRemoving a block
Remove a block from the editor using the removeBlock method.
// Remove a block by its ID
editor.removeBlock('block-to-remove-id');Moving a block
Move a block from one position to another within the editor using the moveBlock method.
// Move a block to a new position
editor.moveBlock('source-block-id', 'target-block-id');Updating a block
Update the properties of an existing block with the updateBlock method. Only the specified properties are modified, while others remain unchanged. It returns true if the update was successful and false otherwise.
// Update block properties
editor.updateBlock('block-id', {
isChecked: true
});Getting a block
Retrieve a block model by its unique identifier using the getBlock method. It returns null if the block is not found.
// Get a specific block
editor.getBlock('block-id');Getting block count
Use the getBlockCount method to retrieve the total number of blocks in the editor.
// Get total block count
editor.getBlockCount();The following example demonstrates the usage of the block editor methods.
import { Component, ViewChild } from '@angular/core';
import { BlockEditorModule, BlockEditorComponent } from "@syncfusion/ej2-angular-blockeditor";
import { BlockModel, ContentType } from "@syncfusion/ej2-blockeditor";
@Component({
imports: [BlockEditorModule],
standalone: true,
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent {
@ViewChild('blockEditorComponent')
public blockEditorComponent!: BlockEditorComponent;
public output = '';
public blocksData = [
{
id: 'block-1',
blockType: 'Heading',
properties: { level: 1},
content: [
{
contentType: ContentType.Text,
content: 'Sample Heading'
}
]
},
{
id: 'block-2',
blockType: 'Paragraph',
content: [
{
contentType: ContentType.Text,
content: 'This is a sample paragraph block.'
}
]
},
{
id: 'block-3',
blockType: 'Paragraph',
content: [
{
contentType: ContentType.Text,
content: 'This is another paragraph block.'
}
]
}
];
//Add Block Method
public addBlock = () => {
const newBlock: BlockModel = {
id: 'new-block',
blockType: 'Paragraph',
content: [{ contentType: ContentType.Text, content: 'This is a newly added block' }]
};
this.blockEditorComponent.addBlock(newBlock, 'block-2', true);
this.displayOutput(`Block added successfully with ID: ${newBlock.id}`);
}
//Remove Block Method
public removeBlock = () => {
this.blockEditorComponent.removeBlock('block-3');
this.displayOutput('Block with ID "block-3" removed successfully');
}
//Get Block Method
public getBlock = () => {
const block = this.blockEditorComponent.getBlock('block-1');
if (block && block.content) {
this.displayOutput(`Block found:\nID: ${block.id}\nType: ${block.blockType}\nContent: ${block.content[0].content}`);
} else {
this.displayOutput('Block with ID "block-1" not found');
}
}
//Move Block Method
public moveBlock = () => {
this.blockEditorComponent.moveBlock('block-2', 'block-1');
this.displayOutput('Block "block-2" moved successfully');
}
//Update Block Method
public updateBlock = () => {
const success = this.blockEditorComponent.updateBlock('block-2', {
indent: 1,
content: [{ content: 'Updated content' }]
});
const updatedBlock = this.blockEditorComponent.getBlock('block-2');
if (success && updatedBlock && updatedBlock.content) {
this.displayOutput(`Block ${updatedBlock.id} updated successfully\nNew content: "${updatedBlock.content[0].content} \nNew indent: ${updatedBlock.indent}"`);
} else {
this.displayOutput('Failed to update block');
}
}
//Get Block Count Method
public getBlockCount = () => {
const count = this.blockEditorComponent.getBlockCount();
this.displayOutput(`Total number of blocks: ${count}`);
}
// Output helper function
displayOutput(message: string): void {
this.output = message;
}
}import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import 'zone.js';
bootstrapApplication(AppComponent).catch((err) => console.error(err));<div id="container">
<ejs-blockeditor id="blockeditor" #blockEditorComponent [blocks]="blocksData" />
<div id="controls">
<h3>Block Management Methods</h3>
<div class="button-group">
<button (click)="addBlock()">Add Block</button>
<button (click)="removeBlock()">Remove Block</button>
<button (click)="getBlock()">Get Block</button>
<button (click)="moveBlock()">Move Block</button>
<button (click)="updateBlock()">Update Block</button>
<button (click)="getBlockCount()">Get Block Count</button>
</div>
<div id="output"></div>
</div>
</div>Selection and Cursor Methods
Setting text selection
Set the text selection within a specific content element using start and end positions with the setSelection method.
// Select text from position 5 to 15 in a content element
editor.setSelection('content-element-id', 5, 15);Setting cursor position
Place the cursor at a specific position within a block using the setCursorPosition method.
// Set cursor at position 10 in a block
editor.setCursorPosition('block-id', 10);Getting selected blocks
Retrieve the currently selected blocks in the editor with the getSelectedBlocks method. It returns null if no blocks are selected.
// Get all selected blocks
editor.getSelectedBlocks();Getting selection range
Get the current selection range in the editor using the getRange method. This method returns a Range object representing the selected text, or null if no selection is active.
// Get current selection range
editor.getRange();Setting selection range
Set the selection range in the editor using the selectRange method. This method accepts a Range object that defines the start and end positions of the selection.
// Create and select a custom range
editor.selectRange(customRange);Selecting a block
Select a specific block in the editor using the selectBlock method.
// Select a complete block
editor.selectBlock('block-id');Selecting all blocks
Select all blocks in the editor using the selectAllBlocks method.
// Select all content in the editor
editor.selectAllBlocks();The following example demonstrates the usage of the selection and cursor methods.
import { Component, ViewChild } from '@angular/core';
import { BlockEditorModule, BlockEditorComponent } from "@syncfusion/ej2-angular-blockeditor";
import { BlockModel, ContentType} from "@syncfusion/ej2-blockeditor";
@Component({
imports: [BlockEditorModule],
standalone: true,
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent {
@ViewChild('blockEditorComponent')
public blockEditorComponent!: BlockEditorComponent;
public output = '';
public blocksData: BlockModel[] = [
{
id: 'heading-block',
blockType: 'Heading',
properties: { level: 1},
content: [
{
contentType: ContentType.Text,
content: 'Welcome to Block Editor'
}
]
},
{
id: 'paragraph-1',
blockType: 'Paragraph',
content: [
{
id: 'paragraph1-content',
contentType: ContentType.Text,
content: 'This is the first paragraph with some sample text content for selection demonstration.'
}
]
},
{
id: 'paragraph-2',
blockType: 'Paragraph',
content: [
{
contentType: ContentType.Text,
content: 'This is the second paragraph that can be used for various selection operations.'
}
]
},
{
id: 'list-block',
blockType: 'BulletList',
content: [
{
contentType: ContentType.Text,
content: 'First list item'
}
]
}
];
// Set Text Selection Method
public setTextSelection = () => {
// Select text from position 5 to 15 in the first paragraph
this.blockEditorComponent.setSelection('paragraph1-content', 5, 15);
this.displayOutput('Text selection set in "paragraph-1" block from position 5 to 15');
}
// Set Cursor Position Method
public setCursor = () => {
// Set cursor at position 10 in the heading block
this.blockEditorComponent.setCursorPosition('heading-block', 10);
this.displayOutput('Cursor position set at position 10 in "heading-block"');
}
// Get Selected Blocks Method
public getSelectedBlocks = () => {
const selectedBlocks = this.blockEditorComponent.getSelectedBlocks();
if (selectedBlocks && selectedBlocks.length > 0) {
const blockInfo = selectedBlocks.map((block: BlockModel) =>
`ID: ${block.id}, Type: ${block.blockType}`
).join('\n');
this.displayOutput(`Selected blocks (${selectedBlocks.length}):\n${blockInfo}`);
} else {
this.displayOutput('No blocks are currently selected');
}
}
// Get Selection Range Method
public getSelectionRange = () => {
const range = this.blockEditorComponent.getRange();
if (range) {
const parent = range.startContainer.nodeType === 3
? (range.startContainer.parentElement as HTMLElement)
: (range.startContainer as HTMLElement);
this.displayOutput(`Current selection range:
blockId: ${(parent as HTMLElement).closest('.e-block')?.id}
Start Container: ${range.startContainer.nodeName}
Start Offset: ${range.startOffset}
End Container: ${range.endContainer.nodeName}
End Offset: ${range.endOffset}
Collapsed: ${range.collapsed}`);
} else {
this.displayOutput('No selection range found');
}
}
// Set Selection Range Method
public setCustomRange = () => {
// Create a custom range for the second paragraph
const paragraphElement = document.getElementById('paragraph-2');
if (paragraphElement) {
const range = document.createRange();
const textNode = (paragraphElement.querySelector('.e-block-content') as HTMLElement).firstChild;
if (textNode) {
range.setStart(textNode, 8);
range.setEnd(textNode, 20);
this.blockEditorComponent.selectRange(range);
this.displayOutput('Custom selection range applied to "paragraph-2" (positions 8-20)');
} else {
this.displayOutput('Could not find text content in paragraph-2');
}
}
}
// Select Block Method
public selectBlock = () => {
// Select the entire heading block
this.blockEditorComponent.selectBlock('heading-block');
this.displayOutput('Entire "heading-block" selected');
}
// Select All Blocks Method
public selectAll = () => {
this.blockEditorComponent.selectAllBlocks();
this.displayOutput('All blocks in the editor have been selected');
}
// Output helper function
displayOutput(message: string): void {
this.output = message;
}
}import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import 'zone.js';
bootstrapApplication(AppComponent).catch((err) => console.error(err));<div id="container">
<ejs-blockeditor id="blockeditor" #blockEditorComponent [blocks]="blocksData" ></div>
<div id="controls">
<h3>Selection and Cursor Methods</h3>
<div class="button-group">
<button (click)="setTextSelection()">Set Text Selection</button>
<button (click)="setCursor()">Set Cursor Position</button>
<button (click)="getSelectedBlocks()">Get Selected Blocks</button>
<button (click)="getSelectionRange()">Get Selection Range</button>
<button (click)="setCustomRange()">Set Selection Range</button>
<button (click)="selectBlock()">Select Block</button>
<button (click)="selectAll()">Select All Blocks</button>
</div>
<div id="output"></div>
</div>
</div>Focus Management Methods
FocusIn
Use the focusIn method to programmatically set focus on the editor, making it ready for user input.
// Focus the editor
editor.focusIn();FocusOut
Use the focusOut method to programmatically remove focus from the editor. This clears any active selections and makes the editor inactive.
// Remove focus from the editor
editor.focusOut();Formatting Methods
Executing toolbar action
Execute a built-in toolbar formatting command using the executeToolbarAction method. Use this to apply formatting such as bold, italic, or color to the selected text.
// Apply bold formatting
editor.executeToolbarAction(BuiltInToolbar.Bold);
// Apply color formatting with a specific value
editor.executeToolbarAction(BuiltInToolbar.Color, '#ff0000');Enabling toolbar items
Enable specific items in the inline toolbar using the enableToolbarItems method. This method accepts a single item or an array of items to enable.
// Enable a specific toolbar item
editor.enableToolbarItems('bold');
// Enable multiple items
editor.enableToolbarItems(['bold', 'italic', 'underline']);Disabling toolbar items
Disable specific items in the inline toolbar using the disableToolbarItems method. This method accepts a single item or an array of items to disable.
// Disable a specific toolbar item
editor.disableToolbarItems('bold');
// Disable multiple items
editor.disableToolbarItems(['bold', 'italic', 'underline']);The following example demonstrates the usage of the formatting and focus methods.
import { Component, ViewChild } from '@angular/core';
import { BlockEditorModule, BlockEditorComponent } from "@syncfusion/ej2-angular-blockeditor";
import { BlockModel, ContentType, CommandName} from "@syncfusion/ej2-blockeditor";
@Component({
imports: [BlockEditorModule],
standalone: true,
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent {
@ViewChild('blockEditorComponent')
public blockEditorComponent!: BlockEditorComponent;
public output = '';
public blocksData: BlockModel[] = [
{
blockType: 'Heading',
properties: { level: 1},
content: [
{
contentType: ContentType.Text,
content: 'Formatting Demo'
}
]
},
{
blockType: 'Paragraph',
content: [
{
contentType: ContentType.Text,
content: 'Select this text and apply different formatting options using the buttons below. You can make text bold or change colors for the text.'
}
]
},
{
blockType: 'BulletList',
content: [
{
contentType: ContentType.Text,
content: 'List item for formatting demonstration'
}
]
}
];
// Apply Bold Formatting
public applyBold = () => {
this.blockEditorComponent.executeToolbarAction(CommandName.Bold);
this.displayOutput('Bold formatting applied to selected text');
}
// Apply Color Formatting
public applyColor = () => {
this.blockEditorComponent.executeToolbarAction(CommandName.Color, '#ff6b35');
this.displayOutput('Orange color (#ff6b35) applied to selected text');
}
// Enable Toolbar Items
public enableToolbarItems = () => {
// Enable specific toolbar items
this.blockEditorComponent.enableToolbarItems(['bold', 'italic', 'underline']);
this.displayOutput('Toolbar items (bold, italic, underline) have been enabled');
}
// Disable Toolbar Items
public disableToolbarItems = () => {
// Disable specific toolbar items
this.blockEditorComponent.disableToolbarItems(['bold', 'italic']);
this.displayOutput('Toolbar items (bold, italic) have been disabled');
}
// Output helper function
displayOutput(message: string): void {
this.output = message;
}
}import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import 'zone.js';
bootstrapApplication(AppComponent).catch((err) => console.error(err));<div id="container">
<ejs-blockeditor id="blockeditor" #blockEditorComponent [blocks]="blocksData" />
<div id="controls">
<h3>Formatting Methods</h3>
<div class="button-group">
<button (click)="applyBold()">Apply Bold </button>
<button (click)="applyColor()">Apply Color</button>
<button (click)="enableToolbarItems()">Enable Toolbar Items</button>
<button (click)="disableToolbarItems()">Disable Toolbar Items</button>
</div>
<div class="instruction">
<p><strong>Instructions:</strong> Select some text in the editor first, then click the formatting buttons to see the effects.</p>
</div>
<div id="output"></div>
</div>
</div>Data Export Methods
Getting data as JSON
Export the editor content in JSON format using the getDataAsJson method. This method allows exporting all blocks or a specific block.
// Get all blocks as JSON
const allBlocks = editor.getDataAsJson();
// Get a specific block as JSON
const specificBlock = editor.getDataAsJson('block-id');Getting data as HTML
Export the editor content in HTML format using the getDataAsHtml method. This method allows exporting all blocks or a specific block.
// Get all blocks as HTML
const allBlocksHtml: string = editor.getDataAsHtml();
// Get a specific block as HTML
const specificBlockHtml: string = editor.getDataAsHtml('block-id');Rendering Blocks from Json
Renders blocks from JSON data using the renderBlocksFromJson method. This method allows either replacing all existing content or inserting at the cursor position.
// Replace all existing content
const replaceAllBlocks = editor.renderBlocksFromJson(jsonData, true);
// Insert at cursor without replacing existing blocks (default behavior)
const insertedAtCursor = editor.renderBlocksFromJson(jsonData);
// Insert after a specific block (only applicable when replace = false)
const insertedAfterTarget = editor.renderBlocksFromJson(jsonData, false, 'target-block-id');Parsing HTML to Blocks
Convert an HTML string into an array of BlockModel objects using the parseHtmlToBlocks method. This method allows transforming HTML content into structured editor blocks.
// Parse HTML into block
const blocks: BlockModel[] = editor.parseHtmlToBlocks(html);Printing editor content
Print the editor content using the print method. This action opens the browser’s print dialog with the current editor content.
// Print the editor content
editor.print();The following example demonstrates the usage of the data export methods.
import { Component, ViewChild } from '@angular/core';
import { BlockEditorModule, BlockEditorComponent } from "@syncfusion/ej2-angular-blockeditor";
import { BlockModel, ContentType } from "@syncfusion/ej2-blockeditor";
@Component({
imports: [BlockEditorModule],
standalone: true,
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent {
@ViewChild('blockEditorComponent')
public blockEditorComponent!: BlockEditorComponent;
public output = '';
public blocksData = [
{
id: 'title-block',
blockType: 'Heading',
properties: { level: 1},
content: [
{
contentType: ContentType.Text,
content: 'Document Export Demo'
}
]
},
{
id: 'intro-paragraph',
blockType: 'Paragraph',
content: [
{
contentType: ContentType.Text,
content: 'This document demonstrates the data export capabilities of the Block Editor. You can export content as JSON or HTML formats.'
}
]
},
{
id: 'features-heading',
blockType: 'Heading',
properties: { level: 2},
content: [
{
contentType: ContentType.Text,
content: 'Export Features'
}
]
},
{
id: 'features-list',
blockType: 'BulletList',
content: [
{
contentType: ContentType.Text,
content: 'JSON export for data processing'
}
]
},
{
id: 'features-list-2',
blockType: 'BulletList',
content: [
{
contentType: ContentType.Text,
content: 'HTML export for web display'
}
]
},
{
id: 'features-list-3',
blockType: 'BulletList',
content: [
{
contentType: ContentType.Text,
content: 'Print functionality for hard copies'
}
]
},
{
id: 'code-example',
blockType: 'Code',
content: [
{
contentType: ContentType.Text,
content: 'const data = editor.getDataAsJson();\nconsole.log(data);'
}
]
}
];
//Get All Data as JSON
public getAllDataJson = () => {
const jsonData = this.blockEditorComponent.getDataAsJson();
const formattedJson = JSON.stringify(jsonData, null, 2);
this.displayOutput(`All blocks as JSON:\n\n${formattedJson}`);
}
// Get Specific Block Data as JSON
public getBlockDataJson = () => {
const blockData = this.blockEditorComponent.getDataAsJson('title-block');
const formattedJson = JSON.stringify(blockData, null, 2);
this.displayOutput(`Block "title-block" as JSON:\n\n${formattedJson}`);
}
// Get All Data as HTML
public getAllDataHtml = () => {
const htmlData = this.blockEditorComponent.getDataAsHtml();
this.displayOutput(`All blocks as HTML:\n\n${htmlData}`);
}
// Get Specific Block Data as HTML
public getBlockDataHtml = () => {
const blockHtml = this.blockEditorComponent.getDataAsHtml('intro-paragraph');
this.displayOutput(`Block "intro-paragraph" as HTML:\n\n${blockHtml}`);
}
// Print Editor Content
public printContent = () => {
this.blockEditorComponent.print();
this.displayOutput('Print dialog opened. Check for a new browser window/tab with the printable content.');
}
// Output helper function
displayOutput(message: string): void {
this.output = message;
}
}import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import 'zone.js';
bootstrapApplication(AppComponent).catch((err) => console.error(err));<div id="container">
<ejs-blockeditor id="blockeditor" #blockEditorComponent [blocks]="blocksData" />
<div id="controls">
<h3>Data Export Methods</h3>
<div class="button-group">
<button (click)="getAllDataJson()">Get All Data as JSON</button>
<button (click)="getBlockDataJson()">Get Block Data as JSON</button>
<button (click)="getAllDataHtml()">Get All Data as HTML</button>
<button (click)="getBlockDataHtml()">Get Block Data as HTML</button>
<button (click)="printContent()">Print Editor Content</button>
</div>
<div id="output"></div>
</div>
</div>