I have to integrate CKEditor into the Blazor 8 application. I have created the Blazor application by choosing the Interactive render mode as Auto.
There are easy steps to integrate the CKEditor in ASP.NET Core but in the case of Blazor 8, I have already spent hours without any luck. Can anyone help me with what I did wrong in my application?
To integrate the CKEditor, I have created a Razor component InputCKEditor.razor.
@inherits InputTextArea@inject IJSRuntime JSRuntime<textarea @attributes="AdditionalAttributes" id="@Id" class="@CssClass" value="@CurrentValue"></textarea>@code { string _id; [Parameter] public string Id { get => _id ?? $"CKEditor_{_uid}"; set => _id = value; } readonly string _uid = Guid.NewGuid().ToString().ToLower().Replace("-", ""); protected override async Task OnAfterRenderAsync(bool firstRender) { if (firstRender) await JSRuntime.InvokeVoidAsync("CKEditorInterop.init", Id, DotNetObjectReference.Create(this)); await base.OnAfterRenderAsync(firstRender); } [JSInvokable] public Task EditorDataChanged(string data) { CurrentValue = data; StateHasChanged(); return Task.CompletedTask; } protected override void Dispose(bool disposing) { JSRuntime.InvokeVoidAsync("CKEditorInterop.destroy", Id); base.Dispose(disposing); }}After that, I created a javascript file CKEditorInterop.js
CKEditorInterop = (() => { var editors = {}; return { init(id, dotNetReference) { window.ClassicEditor .create(document.getElementById(id)) .then(editor => { editors[id] = editor; editor.model.document.on('change:data', () => { var data = editor.getData(); var el = document.createElement('div'); el.innerHTML = data; if (el.innerText.trim() === '') data = null; dotNetReference.invokeMethodAsync('EditorDataChanged', data); }); }) .catch(error => console.error(error)); }, destroy(id) { editors[id].destroy() .then(() => delete editors[id]) .catch(error => console.log(error)); } };})();After that, I registered the CKEditorInterop.js and ckeditor.js on the App.razor page.
<script src="/assets/vendor/ckeditor/ckeditor.js"></script><script src="/js/CKEditorInterop.js"></script><script src="_framework/blazor.web.js"></script>Finally, I have added the InputCKEditor.razor on the Home.razor page.
@page "/"@using CKEditorDemo.Data<PageTitle>Home</PageTitle><h1>CKEditor demo</h1><EditForm Model="@template" FormName="myForm" OnValidSubmit="@HandleValidSubmit" Enhance><InputCKEditor @bind-Value="template.Description" maxlength="2048" style="width:100%;height:150px;"></InputCKEditor><button type="submit">Submit</button></EditForm>@code { private TemplateDTO template = new TemplateDTO(); protected override async Task OnInitializedAsync() { template.Description = "This is a demo."; } private void HandleValidSubmit() { Console.WriteLine(template.Description); }}The TemplateDTO.cs class is as shown below:
public class TemplateDTO{ public string Content { get; set; } = string.Empty;}My above sample code only displays text areas without a rich text editor.