You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular 5 中如何获取CKeditor纯文本内容而非HTML内容

How to Get Plain Text from CKEditor Instead of HTML Content

Hey there! I see you're using CKEditor in your Angular app and want to save plain text instead of the default HTML content. Let's walk through a straightforward solution for this.

First, let's adjust your template to get a reference to the CKEditor instance. Add a template reference variable (#editor) to your <ck-editor> tag:

<ck-editor 
  #editor
  [(ngModel)]='ticket.description' 
  [ngModelOptions]="{standalone: true}" 
  skin="moono-lisa" 
  language="en" 
  [fullPage]="true">
</ck-editor>

Next, in your component file, use ViewChild to access the editor instance. Then create a helper function to convert HTML content to plain text, and use it when you're ready to save the data:

import { Component, ViewChild } from '@angular/core';
import { CKEditorComponent } from '@ckeditor/ckeditor5-angular';

@Component({
  // ... your component metadata
})
export class YourComponent {
  ticket = { description: '' };

  @ViewChild('editor') editor!: CKEditorComponent;

  // Helper function to convert HTML to plain text
  private htmlToPlainText(html: string): string {
    const tempElement = document.createElement('div');
    tempElement.innerHTML = html;
    // textContent is more reliable, fall back to innerText if needed
    return tempElement.textContent || tempElement.innerText || '';
  }

  saveTicket() {
    // Get the raw HTML content from CKEditor
    const htmlContent = this.editor.instance.getData();
    // Convert it to plain text
    const plainTextContent = this.htmlToPlainText(htmlContent);
    // Update your ticket.description with the plain text
    this.ticket.description = plainTextContent;
    
    // Now you can save this.ticket to your database
    // ... your save logic here
  }
}

How this works:

  • The ViewChild gives us direct access to the CKEditor instance, so we can call getData() to get the full HTML content.
  • The htmlToPlainText function uses a temporary DOM element to parse the HTML and extract just the text content—this avoids any manual string parsing that might miss edge cases like nested tags or special characters.
  • When you call saveTicket(), we replace the HTML value in ticket.description with the plain text version before saving to your database.

This approach lets users still use CKEditor's formatting tools during input, but ensures you only store the clean plain text you need for your table display.

内容的提问来源于stack exchange,提问作者user7240891

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 10:05:17