1、Ueditor的集成主要通過把UEditor做成一個Component來實現,先上Component代碼:
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的位置,執行出錯。
2、上面這個代碼里面的UE是一個全局庫,有個比較直接懶的只是讓其可見的聲明方式是如下,細致的接口聲明,同志們自己搞吧:
declare var UE: any;
3、把Ueditor的那兩個js文件ueditor.config.js、ueditor.all.js加進angular-cli的scripts配置項。
4、要把Ueditor用到的靜態資源扔進assets
5、ueditor.config.js中的UEDITOR_HOME_URL改成靜態文件URL父目錄,serverUrl改成后端服務器URL。
最后補一句后端修改點,由於SPA往往跨域部署,后端正常的CORS配置以外,Ueditor會自動把某些調用(config)改成jsonp調用,后端需要根據callback參數做對應額jsonp方式返回響應。最后做個廣告:如果你用Django,推薦DUEditor插件:https://github.com/dhcn/DUEditor