富文本組件是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 hljs from 'highlight.js'
import "node_modules/highlight.js/styles/xcode.css"
@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);
}
}
大致思路:
- 使用ViewChild引用html的dom元素
- 在OnInit的成功后,初始化WangEditor編輯器,把模板中的ElementRef放入到WangEditor的容器中去,讓WangEditor去控制界面的dom操作。
- 實現ControlValueAccessor,讓這個組件支持Angular的表單驗證。
- 實現ngOnDestroy,組件在銷毀的時候,調用WangEditor的destory
4.使用組件
<q-wang-editor [height]="550"></q-wang-editor>
5.效果預覽
6.最后
一個WangEditor的Angular組件封裝就基本完成了。如果需要更多功能,比如圖片上傳,等可以再根據自己的需求增加功能即可
歡迎大家關注我的公眾號【青城同學】和我交流