angular 中使用TinyMCE

1. 安装

npm install --save tinymce

2.在.angular-cli.json中引用

      "scripts": [
         ...
        "../node_modules/tinymce/tinymce.js",
        "../node_modules/tinymce/themes/modern/theme.js",
        "../node_modules/tinymce/plugins/link/plugin.js",
        "../node_modules/tinymce/plugins/paste/plugin.js",
        "../node_modules/tinymce/plugins/table/plugin.js",
        "../node_modules/tinymce/plugins/image/plugin.js",
        "../node_modules/tinymce/plugins/media/plugin.js",
        "../node_modules/tinymce/plugins/textcolor/plugin.js",
        "../node_modules/tinymce/plugins/textpattern/plugin.js",
        "../src/assets/zh_CN.js" //中文包 下载地址:https://www.tinymce.com/download/language-packages/
      ],

3. typing.d.ts中声明tinymce全局变量

declare var tinymce: any;

4. 将 node_modules\tinymce下的skins文件夹 复制到 assets 目录下, 如没有会报错找不到相关css文件

5.在页面中使用

html:

<textarea id="{{elementId}}"></textarea>

ts:

  content: any = 'p'
  elementId: String = 'editortext';
  editor;
  imgurl: any;


ngAfterViewInit(): void {

      let self = this;
      // 初始化富文本框

        // tinymce.updateContent("<p>aaaaaaa<p>")
        tinymce.init({
            selector: '#' + this.elementId,
            height: 400,
            plugins: ['link', 'table', 'image', 'textcolor', 'textpattern', 'media'],
            toolbar: 'insertfile undo redo | styleselect fontsizeselect | forecolor backcolor | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | l  media  image  | print preview fullpage',
            fontsize_formats: '8pt 10pt 12pt 14pt 18pt 24pt 36pt',
            skin_url: 'assets/skins/lightgray',
            media_live_embeds: true,
            // image_dimensions: false,
            relative_urls:false,   //让TinyMCE使用全路径,默认情况下TinyMCE会将主机地址(当链接的地址与当前服务器地址一致的时候)替换掉
            remove_script_host:false, //让TinyMCE使用全路径,默认情况下TinyMCE会将主机地址(当链接的地址与当前服务器地址一致的时候)替换掉
            init_instance_callback : function(editor) {
              setTimeout(function(){
                console.log(self.content);
                if (self.content === undefined) {
                  editor.setContent('');
                } else {
                  editor.setContent(self.content);
                }
              },1000)
            },
            setup: editor => {
                console.log(editor)
                // editor.getContent('<p>aaaaa</p>')
                editor.on('keyup change', () => {

                    const content = editor.getContent();
                    // console.log(editor)
                    console.log(editor.getContent())
                    self.content = editor.getContent()
                    // this.onEditorContentChange.emit(content);
                });
            },
            // 图片上传功能
            images_upload_handler: function(blobInfo, success, failure) {
                var formData;
                formData = new FormData();
                formData.append("file", blobInfo.blob(), blobInfo.filename());
                self.uploadFile(`${environment.host}/admin.php/brand/common/upload`, formData).subscribe( response => {
                  var str = JSON.stringify(response);

                  var selfimgurl = JSON.parse(str)
                    // let url = response.link;
                  success(selfimgurl.link);
                });
            }
        });


  }

    // 上传图片

  private uploadFile(url: string, formData: any) {
      var self = this;
      var headers = new HttpHeaders();
      headers.set("Accept", "application/json");
      return self.http.post(url, formData, { headers: headers });
  }
  ngOnDestroy() {
    tinymce.remove(this.editor);
  }

 

<think>我们使用@tinymce/tinymce-angular库在Angular项目中封装TinyMCE富文本编辑器。首先,我们需要安装必要的依赖:tinymce和@tinymce/tinymce-angular。然后,我们需要将TinyMCE的脚本资源添加到项目中。可以通过将TinyMCE的静态文件放在assets目录下,或者使用CDN。步骤:1.安装依赖npminstalltinymce@tinymce/tinymce-angular2.在angular.json文件中配置TinyMCE的资源路径(假设我们使用本地文件,将node_modules/tinymce目录下的skins、themes、icons等资源复制到assets/tinymce目录下)或者,我们可以通过CDN引入,但这里我们使用本地资源。3.在需要使用富文本编辑器的模块中导入EditorModule。4.在组件中使用<editor>标签,并配置必要的属性,如apiKey(如果使用TinyMCECloud,需要注册获取apiKey,否则可以不用,但会提示需要注册,建议使用本地资源避免提示)。5.由于TinyMCE是付费软件,但我们可以使用开源的社区版(GPL2.0),注意遵守许可证。6.我们这里使用本地资源,因此需要将tinymce.min.js和相关的皮肤、主题等文件放到assets目录下,并在组件中初始化时设置baseURL。完整示例:首先,将node_modules/tinymce目录下的skins、themes、plugins等文件夹复制到项目的assets/tinymce目录下。然后,在组件中配置TinyMCE的初始化选项。下面是一个完整的组件示例:注意:由于angular.json配置静态资源,我们假设已经将tinymce的资源复制到了assets/tinymce下。我们创建一个名为TinymceEditorComponent的组件。</think>### Angular 封装 `@tinymce/tinymce-angular` 完整实现 以下是完整的封装实现,包含配置、主题集成和常用功能: ```typescript // tinymce-wrapper.component.ts import { Component, Input, Output, EventEmitter, OnInit, OnDestroy } from '@angular/core'; import { Editor } from '@tinymce/tinymce-angular'; @Component({ selector: 'app-tinymce-wrapper', template: ` <editor [apiKey]="apiKey" [init]="initConfig" [initialValue]="initialContent" (onInit)="handleInit($event)" (onChange)="handleChange($event)" (onBlur)="handleBlur()" ></editor> `, styles: [` :host { display: block; margin: 1rem 0; } /* 修复移动端高度问题 */ .tox-tinymce { min-height: 300px; } `] }) export class TinymceWrapperComponent implements OnInit, OnDestroy { // API 密钥(免费注册获取) @Input() apiKey = 'your-api-key-here'; // 初始内容 @Input() initialContent = ''; // 配置选项 @Input() config: any = {}; // 内容变更事件 @Output() contentChanged = new EventEmitter<string>(); // 编辑器实例 editorInstance: any; // 默认配置(可被输入属性覆盖) initConfig = { base_url: '/tinymce', // 本地资源路径 suffix: '.min', // 使用压缩版本 height: 500, menubar: true, plugins: [ 'advlist autolink lists link image charmap print preview anchor', 'searchreplace visualblocks code fullscreen', 'insertdatetime media table paste code help wordcount' ], toolbar: 'undo redo | formatselect | bold italic backcolor | \ alignleft aligncenter alignright alignjustify | \ bullist numlist outdent indent | removeformat | help', skin: 'oxide', // 默认皮肤 content_css: 'document', // 使用页面样式 images_upload_handler: this.imageUploadHandler.bind(this), setup: (editor: any) => { this.editorInstance = editor; } }; ngOnInit() { // 合并自定义配置 this.initConfig = { ...this.initConfig, ...this.config }; // 加载本地资源(需要将node_modules/tinymce复制到assets) this.initConfig.base_url = '/assets/tinymce'; } ngOnDestroy() { if (this.editorInstance) { this.editorInstance.remove(); } } // 图片上传处理 imageUploadHandler(blobInfo: any, success: (url: string) => void, failure: (msg: string) => void) { // 实现你的上传逻辑 console.log('上传图片:', blobInfo.filename()); // 模拟上传成功(实际项目替换为真实API) setTimeout(() => { success('https://via.placeholder.com/300x150'); }, 2000); } // 初始化完成 handleInit(event: any) { console.log('TinyMCE初始化完成', event); } // 内容变更 handleChange(event: any) { this.contentChanged.emit(event.editor.getContent()); } // 失去焦点 handleBlur() { console.log('编辑器失去焦点'); } // 插入内容方法(可在父组件调用) insertContent(content: string) { if (this.editorInstance) { this.editorInstance.insertContent(content); } } } ``` ```html <!-- 在父组件中使用 --> <!-- app.component.html --> <app-tinymce-wrapper [initialContent]="'<h2>欢迎使用富文本编辑器</h2><p>开始编辑内容...</p>'" [config]="customConfig" (contentChanged)="onContentChange($event)" ></app-tinymce-wrapper> ``` ```typescript // app.component.ts import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html' }) export class AppComponent { customConfig = { height: 400, toolbar: 'bold italic | link image | code', plugins: 'link image code' }; onContentChange(content: string) { console.log('内容变更:', content); // 这里可以保存内容到数据库 } } ``` ### 关键配置说明 1. **资源加载**: - 本地资源:将 `node_modules/tinymce` 复制到 `assets/tinymce` - CDN 加载:设置 `initConfig.base_url = 'https://cdn.tiny.cloud/1/YOUR_API_KEY/tinymce/6'` 2. **常用插件**: - 表格:`table` - 代码块:`codesample` - 全屏:`fullscreen` - 自动链接:`autolink` - 媒体嵌入:`media` 3. **安全配置**: ```typescript initConfig: { // 允许所有HTML标签 valid_elements: '*[*]', // 防止自动转换特殊字符 entity_encoding: 'raw', // XSS防护 extended_valid_elements: 'script[src|type]' } ``` 4. **主题集成**: ```typescript // 匹配应用主题 skin: 'oxide-dark', content_css: '/assets/editor-styles.css' ``` ### 部署前准备 1. **获取API密钥**: - 访问 [TinyMCE 官网](https://www.tiny.cloud/) 注册免费账户 - 在仪表盘创建应用获取API密钥 2. **资源安装**: ```bash npm install tinymce @tinymce/tinymce-angular ``` 3. **复制资源文件**: ```bash cp -r node_modules/tinymce ./src/assets/tinymce ``` 4. **模块注册**: ```typescript // app.module.ts import { EditorModule } from '@tinymce/tinymce-angular'; @NgModule({ imports: [ EditorModule // 添加编辑器模块 ] }) ``` ### 常见问题解决方案 1. **资源加载失败**: ```typescript // 在angular.json中添加 "assets": [ { "glob": "**/*", "input": "node_modules/tinymce", "output": "/tinymce" } ] ``` 2. **移动端适配**: ```css /* 全局样式 */ @media (max-width: 768px) { .tox-tinymce { height: 300px !important; } } ``` 3. **内容绑定问题**: ```typescript // 强制更新内容 setTimeout(() => { this.editorInstance.setContent(this.initialContent); }); ``` 4. **自定义插件**: ```typescript setup: (editor) => { editor.ui.registry.addButton('customButton', { text: '插入签名', onAction: () => editor.insertContent('{{signature}}') }); } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值