Angular 9中如何访问CKEDITOR对象并添加打印插件?
解决方案
1. 修正HTML模板的错误
你的模板中同时使用了data="allBills"和[(ngModel)]="allBills",这会导致数据绑定冲突,应该移除data属性,因为双向绑定会自动同步数据。另外,确保readOnly设置符合你的需求(只读模式下Print按钮仍可使用,但工具栏其他按钮会被禁用):
<form> <ckeditor #myEditor name="myEditor" editorUrl='https://cdn.ckeditor.com/4.19.1/full/ckeditor.js' id="myEditor" readOnly="true" [(ngModel)]="allBills" [config]="editorConfig" (ready)="onEditorReady($event)"> </ckeditor> </form>
2. 在组件中正确访问编辑器实例与配置
方式一:通过ready事件获取实例并修改配置
在component.ts中:
import { Component, ViewChild } from '@angular/core'; import { CKEditorComponent } from 'ckeditor4-angular'; @Component({ // 组件元数据(如selector、templateUrl等) }) export class YourComponent { allBills: string = ''; // 初始配置,直接定义包含Print按钮的工具栏 editorConfig = { toolbar: [ { name: 'document', items: ['Print'] } ] }; @ViewChild('myEditor') editor: CKEditorComponent; onEditorReady(event: any) { // event即为CKEditor实例,可直接操作配置 const editorInstance = event; // 若需动态调整配置,比如添加更多按钮 // editorInstance.config.toolbar.push({ name: 'basicstyles', items: ['Bold', 'Italic'] }); // 验证配置是否生效 console.log(editorInstance.config.toolbar); } }
方式二:通过ViewChild在AfterViewInit中动态修改
import { Component, ViewChild, AfterViewInit } from '@angular/core'; import { CKEditorComponent } from 'ckeditor4-angular'; @Component({ // 组件元数据 }) export class YourComponent implements AfterViewInit { allBills: string = ''; editorConfig = { toolbar: [] // 先设置空工具栏,后续动态配置 }; @ViewChild('myEditor') editor: CKEditorComponent; ngAfterViewInit(): void { // 等待编辑器异步加载完成,避免实例未初始化 setTimeout(() => { if (this.editor.instance) { // 直接修改工具栏配置 this.editor.instance.config.toolbar = ['Print']; // 刷新工具栏使配置生效 this.editor.instance.destroyToolbar(); this.editor.instance.createToolbar(); } }, 1000); } }
3. 解决工具栏无内容的问题
你之前的配置写法本身没问题,工具栏为空大概率是以下原因:
- 编辑器未加载完成就应用了配置:通过
ready事件设置配置可彻底避免这个问题 - 配置格式冗余:可简化为更直接的数组格式,比如
toolbar: ['Print'] - 只读模式误解:
readOnly="true"只会禁用编辑类按钮,Print按钮不受影响,若需显示其他按钮,需调整只读设置
4. 为什么直接声明CKEDITOR会报错?
ckeditor4-angular采用异步加载CKEditor核心库,全局CKEDITOR对象只有在编辑器完全加载后才会存在,直接在组件初始化阶段访问必然会出现"未定义"错误,必须通过组件的ready事件或等待实例初始化完成后才能访问。
内容的提问来源于stack exchange,提问作者dharani kumar
相关产品推荐
相关产品推荐

