首页 文章

如何动态设置内容到TinyMCE编辑器

提问于
浏览
0

我正在尝试根据下拉菜单中的选定选项动态设置内容到TinyMCE编辑器 .

<app-tinymce [elementId]="'myEditor'" [content]="myContentVar"></app-tinymce>

每次更改下拉菜单选项时,变量 myContentVar 都会正确更新 .

onSelectionChanged(selectedValue: string){
    this.myContentVar = selectedValue;
}

但是,TinyMCE编辑器总是显示空白 . {{myContentVar}} 确实显示正确的值 .

以下是TinyMCE的配置设置 .

tinymce.init({
      selector: '#' + this.elementId,
      plugins: ['link image code charmap preview anchor'],
      toolbar: 'undo redo |  formatselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent',

      setup: editor => {
        this.editor = editor;

        editor.on('change', () => {
          const content = editor.getContent();
          this.editorContent = content;
          this.onEditorContentChange.emit(content);
          this.onModelChange(content);
          this.onTouch(content);

          if (this._controlContainer) {
            if (this.formControlName) {
              this.control = this._controlContainer.control.get(this.formControlName);
              if (this.control) {
                this.control.setValue(new RichFieldTextModel(this.formControlName, this.elementId, this.editorContent));
              }
            }
          }
        });
      }
    });

1 回答

  • 0

    您正在处理的问题是,一旦TinyMCE在页面上实例化,它将不会回头查看 <textarea> 以查看是否已更改 .

    您的示例中的 "on change" 代码专注于将TinyMCE中的最新内容放回到底层表单字段中,因为编辑器中的内容已更改 . 在任何现代框架(如Vue,React或Angular)中注入TinyMCE时,这种情况很常见 . 基于您的代码没有发生的事情是反向 - 当表单字段更改时更新TinyMCE .

    我建议使用TinyMCE的API(特别是 setContent() )在更改选择列表时更新编辑器 . 执行 setContent() 后,使用该API将触发现有代码更新基础表单字段 .

    如果页面上只有一个TinyMCE实例,您可以使用以下内容:

    onSelectionChanged(selectedValue: string){
        //assumes selectedValue is the HTML you want to insert
        tinymce.activeEditor.setContent(selectedValue);  
    }
    

相关问题