Angular10集成ngx-summernote回调不生效及JQuery类型错误问题
Angular 10 集成ngx-summernote图片上传及回调异常解决方案
问题1:onImageUpload、onImageLinkInsert回调不触发
原因是普通函数声明的回调中,this指向config配置对象而非组件实例,且回调上下文脱离了Angular执行环境,修改方案:
- 所有回调改用箭头函数绑定正确的this指向
- 注入NgZone确保回调逻辑在Angular变更检测上下文中执行
问题2:Property 'summernote' does not exist on type 'JQuery' 报错
这是TypeScript缺少summernote类型定义导致,按以下步骤修复:
- 安装类型依赖:
npm install @types/summernote --save-dev - 打开
tsconfig.app.json,在compilerOptions.types数组中添加summernote - 确认
angular.json中资源引入顺序正确:先引入jQuery,再引入summernote的js和css资源:
"styles": [ "node_modules/summernote/dist/summernote-lite.min.css", "src/styles.scss" ], "scripts": [ "node_modules/jquery/dist/jquery.min.js", "node_modules/summernote/dist/summernote-lite.min.js" ]
问题3:代码逻辑修复及NgZone使用
第一步:组件导入与注入
import { Component, NgZone, ViewChild } from '@angular/core'; import { NgxSummernoteDirective } from 'ngx-summernote'; import { HttpClient } from '@angular/common/http'; // 替换$.ajax更符合Angular规范 @Component({ // 你的原有组件配置 }) export class YourComponent { @ViewChild('refsummernote') summernote: NgxSummernoteDirective; config: any; constructor( private ngZone: NgZone, private http: HttpClient ) { // 初始化配置放在constructor里,确保this绑定正确 this.initSummernoteConfig(); }
第二步:修正后的config配置
initSummernoteConfig() { this.config = { tabsize: 2, height: '300px', toolbar: [ ['misc', ['undo', 'redo']], ['font', ['bold', 'italic', 'underline', 'clear']], ['para', ['style']], ['table', ['table']], ['insert', ['picture', 'link', 'hr']], ], disableDragAndDrop: true, callbacks: { // 改用箭头函数绑定this onImageUpload: (files, editor, welEditable) => { console.log('onImageUpload'); for (let i = files.length - 1; i >= 0; i--) { this.sendFile(files[i]); } }, onImageLinkInsert: (url) => { console.log('onImageLinkInsert'); this.ngZone.run(() => { const img = document.createElement('img'); img.src = url; this.summernote.insertNode(img); }); }, onPaste: (e) => { console.log('onPaste'); this.ngZone.run(() => { const bufferText = ((e.originalEvent || e).clipboardData || window.clipboardData).getData('Text'); e.preventDefault(); document.execCommand('insertText', false, bufferText); }); }, }, }; }
第三步:修正后的文件上传方法
sendFile(file: File) { const form_data = new FormData(); form_data.append('file', file); this.http.post('/img/pdf', form_data, { headers: { "Authorization": "Bearer ****" } }).subscribe((response: any) => { this.ngZone.run(() => { const img = document.createElement('img'); img.src = response.url; img.setAttribute('data-fileId', response.id); this.summernote.insertNode(img); }); }); }
第四步:模板代码无需修改
<textArea formControlName="html" #refsummernote id="summernote" [ngxSummernote]="config"></textArea>
核心注意点
- 不要直接操作jQuery调用summernote方法,通过@ViewChild获取ngx-summernote指令实例调用官方提供的API更稳定,避免类型报错
- 所有summernote回调里的业务逻辑都包裹在
ngZone.run()中,确保Angular可以捕获到变更,避免视图不更新或者回调不执行的问题 - 替换$.ajax为Angular的HttpClient,统一请求管理,避免额外的上下文绑定问题
内容的提问来源于stack exchange,提问作者CosentinoWebDev
相关产品推荐
相关产品推荐

