Angular集成UEditor

    一、Ueditor的集成主要经过把UEditor作成一个Component来实现,先上Component代码:      javascript

import {
  AfterContentInit, Component, Input, OnDestroy, OnInit
} from '@angular/core';
import {DomSanitizer, SafeHtml} from '@angular/platform-browser';



@Component({
  selector: 'app-ueditor',
  template: '<div [innerHTML]="trustedHtml"></div>'
})
export class UeditorComponent implements OnInit, OnDestroy, AfterViewInit {
  ngOnDestroy(): void {
    this.ueditor.destroy();
    this.ueditor = null;
  }


  @Input() content: string;
  ueditor: any;

  trustedHtml: SafeHtml;
  constructor(private sanitizer: DomSanitizer) {
    // javascript: URLs are dangerous if attacker controlled.
    // Angular sanitizes them in data binding, but you can
    // explicitly tell Angular to trust this value:
  }
  ngOnInit(): void {
    const html = '<script id="textdescription" name="content"  style="display: inline-block;" type="text/plain">' + this.content + '</script>';
    this.trustedHtml = this.sanitizer.bypassSecurityTrustHtml(html);

  }
  ngAfterViewInit(): void {
    this.ueditor = UE.getEditor('textdescription', {'initialFrameHeight': 580});
    //console.log(this.ueditor);
  }


}

 

   简单解释一下,这个代码干了啥,用DomSanitizer这个组件把原本模板中不合法的Script标签合法化,并且只能经过属性绑定的赋值,才能让模板把它渲染出来。Ng的模板自带XSS过滤,像Script标签会被直接省略掉,致使的结果是UE找不到holder的位置,执行出错。html

   二、上面这个代码里面的UE是一个全局库,有个比较直接懒的只是让其可见的声明方式是以下,细致的接口声明,同志们本身搞吧:java

declare var UE: any;

      三、把Ueditor的那两个js文件ueditor.config.js、ueditor.all.js加进angular-cli的scripts配置项。git

      四、要把Ueditor用到的静态资源扔进assetsgithub

      五、ueditor.config.js中的UEDITOR_HOME_URL改为静态文件URL父目录,serverUrl改为后端服务器URL。json

      最后补一句后端修改点,因为SPA每每跨域部署,后端正常的CORS配置之外,Ueditor会自动把某些调用(config)改为jsonp调用,后端须要根据callback参数作对应额jsonp方式返回响应。最后作个广告:若是你用Django,推荐DUEditor插件:https://github.com/dhcn/DUEditor后端

相关文章
相关标签/搜索