Angular封裝WangEditor富文字元件的方法
阿新 • • 發佈:2021-08-02
富文字元件是web程式中很常用的一個元件,特別是要開發一個部落格,論壇這類的後臺。
得益於Angular的強大,封裝WangEditor元件非常簡單
1.使用yarn或者npm安裝wangeditor
yarn add wangeditor
2.建立一個Angular的元件
ng g c q-wang-editor
3.封裝元件邏輯
3.1 模板
<div #wang></div>
3.2 ts邏輯
import { Component,ElementRef,EventEmitter,Input,OnDestroy,OnInit,Output,ViewChild,ViewEncapsulation } from '@angular/core'; import { ControlValueAccessor } from '@angular/forms'; import E from "wangeditor" import hl from 'highlight.js' import "node_modules/highlight.js/styles/xcode." @Component({ selector: 'q-wang-editor',templateUrl: './q-wang-editor.component.html',styleUrls: [ './q-wang-editor.component.less','../../../../../node_modules/highlight.js/styles/xcode.css'],encapsulation: ViewEncapsulation.None,}) export class QWangEditorComponent implements OnInit,ControlValueAccessor,OnDestroy { @ViewChild("wang") editor!: ElementRef; @Input() value: string = ''; @Input() height = 300; @Output() valueChange = new EventEmitter(); onChange: ((value: string) => {}) | undefined; html = '' wangEditor: E | undefined; constructor() { } ngOnDestroy(): void { this.wangEditor?.destroy(); } writeValue(obj: any): void { this.html = obj; this.wangEditor?.txt.html(this.html) } registerOnChange(fn: any): void { } registerOnTouched(fn: any): void { } ngOnInit(): void { setTimeout(() => { this.wangEditor = new E(this.editor.nativeElement) this.wangEditor.config.zIndex = 500; this.wangEditor.config.height = this.height this.wangEditor.highlight = hljs; this.wangEditor.config.onchange = (html: any) => { this.valueChange.emit(html) if (this.onChange) { this.onChange(html); } } this.wangEditor.config.onchangeTimeout = 500; this.wangEditor.create(); this.wangEditor.txt.html(this.html) },200); } }
大致思路:
- 使用ViewChilwww.cppcns.comd引用html的dom元素
- 在OnInit的成功後,初始化WangEditor編輯器,把模板中的ElementRef放入到WangEditor的容器中去,讓WangEditor去控制介面的dom操作。
- 實現ControlValueAccessor,讓這個元件支援Angular的表單驗證。
- 實現ngOnDestroy,元件在銷燬的時候,呼叫WangEwww.cppcns.comditor的destory
4.使用元件
<q-wang-editor [height]="550"></q-wang-editor>
5.效果預覽
6.最後
一個WangEditor的Angular元件封裝就基本完成了。如果需要更多功能,比如圖片上傳,等可以再根據自己的需求增加功能即可
到此這篇關於Angular封裝WangEditor富文字元件的文章就介紹到這了,更多相關Angular WangEditor富文字元件內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!