首页 > 解决方案 > ckeditor5:将链接目标设置为 _blank

问题描述

如何让在 ckeditor5 中创建的所有链接都包含 target="_blank" ?

我正在使用 Angular 9 创建一个简单的页面编辑器。最终结果是允许用户编辑填充另一个页面的字段。其中一个元素是带有 html 文本的侧边栏。

页面编辑器包括ckeditor5。基本实现工作。
HTML

<ckeditor [(ngModel)]="SidebarContent" name="SidebarContent" [editor]="Editor" [data]="SidebarContent" #pageSidebarContent="ngModel" ></ckeditor>

组件.ts

...
import * as ClassicEditor from '@ckeditor/ckeditor5-build-classic';
...
public Editor = ClassicEditor;

用户可以在 ckeditor 框中输入文本,单击向上,“文本”保存到数据库,并在其他页面上检索。

但是,用户希望边栏中的链接打开一个新窗口(target="_blank")。

以下文档(解释如何在 html 中实现配置): https ://ckeditor.com/docs/ckeditor5/latest/builds/guides/integration/frameworks/angular.html#using-a-custom-ckeditor-5-建造

所以我将它添加到 HTML

<ckeditor [(ngModel)]="SidebarContent" name="SidebarContent" [editor]="Editor" [data]="SidebarContent" #pageSidebarContent="ngModel" [config]="[{link:{addTargetToExternalLinks:true}}]"></ckeditor>

没变。

该文档有很多关于进行这些编辑的参考:

ClassicEditor
    .create( document.querySelector( '#editor' ) )

我对 component.ts 文件执行了以下操作:

this.Editor.create({
      link: {
        decorators: {
            addTargetToExternalLinks: {
                attributes: {
                    target: '_blank',
                    rel: 'noopener noreferrer'
                }
            }
        }
      }
    })

导致错误:

CKEditorError: datacontroller-init-non-existent-root: Attempting to init data on a non-existing root. Read more: https://ckeditor.com/docs/ckeditor5/latest/framework/guides/support/error-codes.html#error-datacontroller-init-non-existent-root

我无法成功实现 .create ,我可以让 ckeditor 将 target="_blank" 添加到链接中。

标签: angularhyperlinkckeditor5

解决方案


尝试这个:

 <ckeditor [editor]="Editor" [config]="config"[(ngModel)]="text"></ckeditor>

. 并在您的 .ts 中:

config = {
    toolbar: [
      '_',
      'bold',
      'italic',
      'link',
      'bulletedList',
      'numberedList',
    ],
    link : {
      addTargetToExternalLinks: true
    }
  }

如果您希望用户决定每个链接,您的配置应如下所示:

  config = {
language: 'de',
toolbar: [
  '_',
  'bold',
  'italic',
  'link',
  'bulletedList',
  'numberedList',
],
link : {
  addTargetToExternalLinks: true,
  decorators: [
    {
      mode: 'manual',
      label: 'External Link',
      attributes: {
        target: '_blank',
      }
    }
  ]
}

}


推荐阅读