1. 程式人生 > 程式設計 >angular8.5整合TinyMce5的使用和詳細配置(推薦)

angular8.5整合TinyMce5的使用和詳細配置(推薦)

編寫人:mkl

日期:2020.11.16

本篇主要講解的是TinyMce的配置,原理不做講解,請自行查閱文件TinyM

TinyMCE是什麼?

TinyMCE是一款易用、且功能強大的所見即所得的富文字編輯器。同類程式有:UEditor、Kindeditor、Simditor、CKEditor、wangEditor、Suneditor、froala等等。

TinyMCE的優勢:

  • 開源可商用,基於LGPL2.1
  • 外掛豐富,自帶外掛基本涵蓋日常所需功能(示例看下面的Demo-2)
  • 介面豐富,可擴充套件性強,有能力可以無限拓展功能
  • 介面好看,符合現代審美
  • 提供經典、內聯、沉浸無干擾三種模式(詳見“介紹與入門”)
  • 對標準支援優秀(自v5開始)
  • 多語言支援,官網可下載幾十種語言。

高階外掛需要收費,比如:格式刷、檔案上傳、匯出pdf等功能,具體請檢視官方文件;

官網及文件:www.tiny.cloud

官網及文件(中文):http://tinymce.ax-z.cn/ 此文件不全

Github:github.com/tinymce

快速開始

使用第三方類庫 ngx-tinymce

1、git地址

https://github.com/cipchk/ngx-tinymce

2、安裝部署

npm install --save-dev [email protected]

3、初步配置

(1) TinyMCE的自託管發行版可下載,用於開發和生產軟體包

baseURL:需要下載開發包,放到專案中,可自定義配置,如下圖:

https://file.leancloud.biz:4445/CNIC_M/uploadFile/Images/900/yq4kdacf6943b9b74f6db66718500b972393/20201114/16053385528224.png

(2) 像富文字框你可能需要在所有子模組中都會可能會用到,因為建議在 SharedModule模組中匯入和匯出他。

在根模組app.module.ts配置:

import { NgxTinymceModule } from 'ngx-tinymce';
@NgModule({
 imports: [
 BrowserModule,NgxTinymceModule.forRoot({
 baseURL: './assets/library/tinymce/'
 })
 ]
})
export class AppModule { }

4、詳細配置

(1) Html模板檔案test.component.html中新增配置:

<tinymce [(ngModel)]="html" [config]="initConfig"></tinymce>

(2) test.component.ts新增配置:

引入:import { NgxTinymceModule } from 'ngx-tinymce';

宣告配置變數:public initConfig: any;

// 初始化元件
initTinymce() {
	this.initConfig = {
	 // 佔位符
	 placeholder: '請輸入內容',// 高度 max_height,max_width,min_height,min_width
	 min_height: 600,// 編輯器底邊距
	 // autoresize_bottom_margin: 50,// 編輯器body部分距離左右2邊的距離
	 // autoresize_overflow_padding: 50,// 面板 與assets\library\tinymce\skins\ui 下資料夾對應,
	 // 黑色
	 // skin: 'oxide-dark',// 面板路徑
	 // skin_url: '/css/mytinymceskin'
	 
	 // 換行時,是否保留當前樣式
	 keep_styles: true,// html版本
	 // 該值預設是html5,可選值還有:html4、html5-strict。
	 // html5模式是完整的HTML5規範,它相容舊的HTML4。html5-strict是HTML5的嚴格模式,它只允許HTML5規範的元素,不包括已經被移除標準的元素。html4模式則是包括完整的HTML4過渡規範。在需要相容老舊瀏覽器時,可能會用到該選項。
	 schema: 'html5',// 隱藏狀態列 取消底部標籤和元件介紹資訊 狀態列是與編輯器的可編輯區域底部對齊的灰色欄。狀態列包含路徑資訊和調整大小手柄。刪除狀態列將使使用者無法更改可編輯區域的大小。
	 statusbar: true,// 是否允許改變高度,statusbar必須為true,預設: true(僅允許改變高度),false(完全不讓你動),'both'(寬高都能改變,注意引號)
	 resize: true,// 禁用狀態列的元素路徑顯示
	 elementpath: false,// 禁用狀態列資訊 使用該branding選項可以禁用狀態列中顯示的“由Tiny提供支援”連結,以進行產品歸因。重要提示:免費和開放原始碼使用者必須提供產品歸因。有關TinyMCE歸屬要求的資訊,請參閱:徽標和歸屬要求。
	 branding: false,// 編輯區的樣式,也可以指定css檔案 預設:default dark(暗色背景) document(類似word) writer(類似word,只是比word寬一點)
	 // content_css : '/mycontent.css',// content_css: 'document',// 語言
	 language: 'zh_CN',// 瀏覽器的拼寫檢查
	 // browser_spellcheck: true,// 支援滑鼠右鍵的元件
	 contextmenu: 'link image table media',// 禁用滑鼠右鍵時開啟瀏覽器選單彈框,配合contextmenu使用,否則右鍵不彈框
	 contextmenu_never_use_native: true,// 對話方塊支援拖動
	 draggable_modal: true,// 開啟拖入功能,true:禁止拖入
	 paste_block_drop: false,// 允許貼上圖片
	 paste_data_images: true,// 禁用預設貼上過濾器
	 paste_enable_default_filters: false,paste_filter_drop: false,// 禁用樣式貼上過濾器
	 paste_remove_styles_if_webkit: false,// 檢測類似於URL的文字,然後將其更改為超連結。
	 // 檢測類似於影象URL的文字,並嘗試用影象替換文字。
	 smart_paste: true,// 貼上前的處理
	 paste_preprocess: (plugin,args) => {
		// console.log(args.content);
	 },// 貼上到元件後,新增dom屬性,元件預設添加了div,通過控制檯可以看出該位置的div的id為12了
	 paste_postprocess: (plugin,args) => {
		// console.log(args.node);
		// args.node.setAttribute('id','42');
	 },// 允許貼上的元素,不管用
	 // paste_word_valid_elements: 'strong,h1,h2',// 圖片高階功能
	 image_advtab: true,// 圖片對話方塊中上傳標籤開關,false時只可以輸入圖片路徑,沒有上傳入口
	 image_uploadtab: true,// 是否開啟圖片標題設定的選擇,這裡設定否
	 image_title: false,// 啟用或禁用自動上傳URL或Blob URI表示的影象
	 automatic_uploads: true,// 自動生成圖片名稱
	 images_reuse_filename: true,// 預設圖片列表
	 // image_list: (success) => {
	 // success([
	 // {title: '狗',value: 'mydog.jpg'},// {title: '貓',value: 'mycat.gif'}
	 // ]);
	 // },// 圖片樣式列表
	 // image_class_list: [
	 // {title: '無',value: ''},// {title: 'dog',value: 'dog_class'},// {title: 'cat',value: 'cat_class'}
	 // ],// 是否開啟自動儲存,退出頁面或重新整理時提示
	 autosave_ask_before_unload: true,// 自動儲存時間間隔 秒
	 autosave_interval: '30s',// 本地儲存資料的有效期 分
	 autosave_retention: "5m",// 元件崩潰後是否自動還原最後儲存的內容
	 autosave_restore_when_empty: true,// 自定義快速工具欄
	 // quickbars_selection_toolbar: 'bold italic | formatselect | quicklink blockquote',// 禁用快速工具欄
	 quickbars_selection_toolbar: false,// 目錄級別個數H1通過H9
	 toc_depth: 9,// 自定義目錄標籤包裹,預設是H2
	 // toc_header: 'div',// 目錄樣式
	 // toc_class: 'myclass',// 粘性工具欄(或停靠工具欄),當向下滾動網頁直到不再可見編輯器時,會將工具欄和選單停靠在螢幕頂部。
	 toolbar_sticky: true,// 工具欄位置 auto,top,bottom
	 toolbar_location: 'top',// 工具欄的樣式 'floating','sliding','scrolling',或者'wrap'
	 toolbar_mode: 'floating',// 從選單欄中刪除選單
	 // removed_menuitems: 'undo,redo',// 禁用選單欄
	 // menubar: false,// 設定模板,可以寫路徑,通過後端返回該格式的陣列資料
	 // templates:'http://192.168.9.22:18085/testAction/getTemplats',templates: [
		// content:html字串資料
		{title: 'Some title 1',description: 'Some desc 1',content: '<p style="margin: 0cm; margin-bottom: .0001pt; text-align: center;" align="center"><span style="font-size: 14.0pt; font-family: 黑體;">我的模板1</span></p>'},// url:html檔案
		{title: 'Some title 2',description: 'Some desc 2',url: '../../assets/templates/10218060374200.html'}
	 ],// 類名稱
	 template_cdate_classes: "cdate creationdate",// 模板日期格式設定
	 template_cdate_format: "%m/%d/%Y - %H:%M:%S",// 元件,在這裡配置的元件才會生效
	 plugins: [
		'toc advlist','autolink lists link image charmap print preview anchor template','searchreplace visualblocks code fullscreen pagebreak media','insertdatetime table paste code help wordcount imagetools directionality autosave emoticons hr searchreplace codesample visualchars'
	 ],// 工具欄分類 
	 menubar: 'file edit insert view format table help export',menu: {
		file: { title: 'File',items: 'newdocument undo redo | preview | print ' },edit: { title: 'Edit',items: 'undo redo | cut copy paste | selectall | searchreplace' },view: { title: 'View',items: 'code | visualaid visualchars visualblocks | spellchecker | fullscreen codesample' },insert: { title: 'Insert',items: 'image link media template codesample inserttable | charmap emoticons hr | pagebreak nonbreaking anchor toc | insertdatetime' },format: { title: 'Format',items: 'bold italic underline strikethrough superscript subscript codeformat | formats blockformats fontformats fontsizes align lineheight | forecolor backcolor | removeformat' },tools: { title: 'Tools',items: 'spellcheckerlanguage | code wordcount' },table: { title: 'Table',items: 'inserttable | cell row column | tableprops deletetable' },help: { title: 'Help',items: 'help' },// 自定義選單
		export: { title: '匯出',items: 'word pdf' }
	 },// 工具欄圖示
	 toolbar1:
		'undo redo | formatselect | fontselect fontsizeselect lineheight | bold italic underline strikethrough forecolor backcolor | \
		alignleft aligncenter alignright alignjustify removeformat | preview template codesample remove selectall link image fullscreen',toolbar2:
		'bullist numlist quicktable outdent indent | anchor restoredraft emoticons hr pagebreak searchreplace toc | help',// 自定義選單按鈕 https://www.tiny.cloud/docs/ui-components/menuitems/#howtocreatecustommenuitems
	 setup: (editor) => {
		// 基本選單
		editor.ui.registry.addMenuItem('word',{
		 text: 'word',onAction: () => {
			this.downWord();
		 }
		});
		editor.ui.registry.addMenuItem('pdf',{
		 text: 'pdf',onAction: () => {
			this.downPdf();
		 }
		});
		// 巢狀選單
		// editor.ui.registry.addNestedMenuItem('nesteditem',{
		// text: 'My nested menu item',// getSubmenuItems: () => {
		// return [{
		// type: 'menuitem',// text: 'My submenu item',// onAction: () => {
		// alert('Submenu item clicked');
		// }
		// }];
		// }
		// });
		// 切換選單,如:設定on、off狀態的 
		// editor.ui.registry.addToggleMenuItem('toggleitem',{
		// text: 'My toggle menu item',// icon: 'home',// onAction: () => {
		// this.toggleState = !this.toggleState;
		// alert('Toggle menu item clicked');
		// },// onSetup: (api) => {
		// api.setActive(this.toggleState);
		// return () => {};
		// }
		// });
	 },// 顏色列表列數
	 color_cols: 4,// 關閉編輯器預設顏色
	 
	 // custom_colors: false,// 自定義顏色配置 自定義顏色後,不會顯示調色盤
	 // color_map: [
	 // "000000","Black",// "993300","Burnt orange",// "333300","Dark olive",// "003300","Dark green",// "003366","Dark azure",// "000080","Navy Blue",// "333399","Indigo",// "333333","Very dark gray",// "800000","Maroon",// ],// 撤銷次數,預設無限次
	 custom_undo_redo_levels: 30,// 行高 5.5版本後支援
	 lineheight_formats: '1 1.1 1.2 1.3 1.4 1.5 2',// 字型
	 font_formats: 
					'宋體=simsun,serif;' +
					'仿宋=FangSong,serif;' + 
					'新宋體=NSimSun,serif;' + 
					'黑體=SimHei,serif;' + 
					'楷體=KaiTi,serif;' + 
					'微軟雅黑=Microsoft YaHei,Helvetica Neue,PingFang SC,sans-serif;' + 
					'隸書=LiSu,serif;' + 
					'幼圓=YouYuan,serif;' + 
					'華文細黑=STXihei,serif;' + 
					'華文楷體=STKaiti,serif;' + 
					'華文宋體=STSong,serif;' +
					// 預設字型
					'Andale Mono=andale mono,times; Arial=arial,helvetica,sans-serif; Arial Black=arial black,avant garde; Book Antiqua=book antiqua,palatino; Comic Sans MS=comic sans ms,sans-serif; Courier New=courier new,courier; Georgia=georgia,palatino; Helvetica=helvetica; Impact=impact,chicago; Symbol=symbol; Tahoma=tahoma,arial,sans-serif; Terminal=terminal,monaco; Times New Roman=times new roman,times; Trebuchet MS=trebuchet ms,geneva; Verdana=verdana,geneva; Webdings=webdings; Wingdings=wingdings,zapf dingbats',// 字號
	 fontsize_formats: '8pt 10pt 12pt 14pt 18pt 24pt 36pt',// 如果表格border為0,TinyMCE會在編輯區內的表格周圍新增虛線框作為視覺輔助
	 visual: true,// 支援本地圖片上傳
	 powerpaste_allow_local_images: true,// 此設定控制如何過濾從Microsoft Word貼上的內容。
	 // clean-保留標題,表格和列表等內容的結構,但刪除內聯樣式和類。這樣就產生了使用站點CSS樣式表的簡單內容,同時保留了原始文件的語義結構。
	 // merge-保留原始文件的內聯格式和結構。無效和專有的樣式,標記和屬性仍會被刪除,以確保HTML有效,同時更緊密地匹配原始文件格式。
	 // prompt -在嘗試貼上單詞內容後提示使用者在“清理”和“合併”選項之間進行選擇
	 // powerpaste_word_import: 'prompt',// powerpaste_html_import: 'prompt',// 貼上為文字按鈕的初始狀態,開啟後,只會貼上文字內容
	 paste_as_text: false,// 合併相同元素的內容
	 paste_merge_formats: false,// 多少空格來表示HTML中的製表符
	 paste_tab_spaces: 2,// 媒體實時預覽開關 開啟此選項後,使用者可看到編輯區內嵌入視訊的實時預覽,而不是佔位圖,此設定對video無效
	 media_live_embeds: true,// 自定義媒體樣式 http://tinymce.ax-z.cn/plugins/media.php
	 video_template_callback: (data) => {
		return '<video width="' + data.width + '" height="' + data.height 
		+ '"' + (data.poster ? ' poster="' + data.poster + '"' : '')
		+ ' controls="controls">\n' + '<source src="' + data.source1 + '"' 
		+ (data.source1mime ? ' type="' + data.source1mime + '"' : '') + ' />\n' 
		+ (data.source2 ? '<source src="' + data.source2 + '"' 
		+ (data.source2mime ? ' type="' + data.source2mime + '"' : '') + ' />\n' : '') 
		+ '</video>';
	 },// 檢查URL是否包含特殊內容,如包含則生成自定義的iframe,否則交給外掛的預設邏輯生成預設程式碼
	 media_url_resolver: (data,resolve) => {
		if (data.url.indexOf('YOUR_SPECIAL_VIDEO_URL') !== -1) {
			const embedHtml = '';
			resolve({html: embedHtml});
		}else{
			resolve({html: ''});
		}
	 },// 分頁
	 pagebreak_separator: '<!-- my page break -->',// 拆分塊元素
	 pagebreak_split_block: true,// 為編輯區錨點自定義樣式 my-custom-class是樣式名
	 visual_anchor_class: 'my-custom-class',// 為編輯區表格自定義樣式
	 visual_table_class: 'my-custom-class',// 程式碼示例列表,可以根據插入的文字內容,適配合適的樣式,比如java程式碼和html樣式區分開來
	 // codesample_languages: [
	 // {text: 'HTML/XML',value: 'markup'},// {text: 'JavaScript',value: 'javascript'},// {text: 'CSS',value: 'css'},// {text: 'PHP',value: 'php'},// 自定義示例樣式
	 // codesample_content_css: '/static/prism.css',// 禁止輸入字元
	 // media_alt_source: true,// 禁用視訊
	 // media_filter_html: false,// 可以預覽視訊
	 // media_live_embeds: true,// 禁用Poster媒體對話方塊中的輸入欄位
	 // media_poster: true,// 自定義監聽圖片上傳
	 images_upload_handler: (blobInfo,succFun,failFun) => {
		let xhr;
		let formData;
		const file = blobInfo.blob();
		xhr = new XMLHttpRequest();
		xhr.withCredentials = false;
		xhr.open(
		 'POST',// 上傳圖片伺服器地址
		 'https://file.test.biz:4443/******',);
		xhr.onload = () => {
		 let json;
		 if (xhr.status !== 200) {
			failFun('HTTP Error: ' + xhr.status);
			return;
		 }
		 json = JSON.parse(xhr.responseText);
		 // 這裡是圖片伺服器返回的圖片地址,需要根據實際情況自己處理
		 succFun(
			'https://file.test.biz:4445/' +
			 json.listData[0].cDirRelativePath +
			 '/' +
			 json.listData[0].cUpDocumentName,);
		};
		formData = new FormData();
		formData.append('file',file,file.name);
		// 將圖片顯示到富文字編輯器中
		xhr.send(formData);
	 }
	};
}

法中呼叫初始化方法:

this.initTinymce();

5、通過以上配置,啟動服務,應該就可以看到效果了。

https://file.leancloud.biz:4445/CNIC_M/uploadFile/Images/900/yq4kdacf6943b9b74f6db66718500b972393/20201114/16053408398933.png?1605340839881

6、這些配置不保證沒有錯誤,在使用時,請根據實際情況做相應的調整;

7、如果有錯誤或者不合理的地方,歡迎指正。

8、本文只是TinyMce的配置和使用方法,預計後期我還會出一篇文章,主要內容是,在學習TinyMce時遇到的坑、存在的問題和解決辦法;

9、匯出PDF和Word功能後端介面已經實現,做了簡單封裝,同時,匯出按鈕也整合到了富文字元件內,匯出功能的實現專門做一篇文章去描述。

https://file.leancloud.biz:4445/CNIC_M/uploadFile/Images/900/yq4kdacf6943b9b74f6db66718500b972393/20201114/16053412701597.png?1605341269976

10、轉載請標明出處。

到此這篇關於angular8.5整合TinyMce5的使用和詳細配置的文章就介紹到這了,更多相關angular8.5整合TinyMce5內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!