Angular 5 中如何获取CKeditor纯文本内容而非HTML内容
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
ViewChildgives us direct access to the CKEditor instance, so we can callgetData()to get the full HTML content. - The
htmlToPlainTextfunction 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 inticket.descriptionwith 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

