富文字元件是web程式中很常用的一個元件,特別是要開發一個部落格,論壇這類的網站後臺。

得益於Angular的強大,封裝WangEditor元件非常簡單

1.使用yarn或者npm安裝wangeditor

  1. yarn add wangeditor

2.建立一個Angular的元件

  1. ng g c q-wang-editor

3.封裝元件邏輯

3.1 模板

  1. <div #wang></div>

3.2 ts邏輯

  1. import { Component, ElementRef, EventEmitter, Input, OnDestroy, OnInit, Output, ViewChild, ViewEncapsulation } from '@angular/core';
  2. import { ControlValueAccessor } from '@angular/forms';
  3. import E from "wangeditor"
  4. import hljs from 'highlight.js'
  5. import "node_modules/highlight.js/styles/xcode.css"
  6. @Component({
  7. selector: 'q-wang-editor',
  8. templateUrl: './q-wang-editor.component.html',
  9. styleUrls: [
  10. './q-wang-editor.component.less',
  11. '../../../../../node_modules/highlight.js/styles/xcode.css'],
  12. encapsulation: ViewEncapsulation.None,
  13. })
  14. export class QWangEditorComponent implements OnInit, ControlValueAccessor,OnDestroy {
  15. @ViewChild("wang")
  16. editor!: ElementRef;
  17. @Input() value: string = '';
  18. @Input() height = 300;
  19. @Output() valueChange = new EventEmitter();
  20. onChange: ((value: string) => {}) | undefined;
  21. html = ''
  22. wangEditor: E | undefined;
  23. constructor() { }
  24. ngOnDestroy(): void {
  25. this.wangEditor?.destroy();
  26. }
  27. writeValue(obj: any): void {
  28. this.html = obj;
  29. this.wangEditor?.txt.html(this.html)
  30. }
  31. registerOnChange(fn: any): void {
  32. }
  33. registerOnTouched(fn: any): void {
  34. }
  35. ngOnInit(): void {
  36. setTimeout(() => {
  37. this.wangEditor = new E(this.editor.nativeElement)
  38. this.wangEditor.config.zIndex = 500;
  39. this.wangEditor.config.height = this.height
  40. this.wangEditor.highlight = hljs;
  41. this.wangEditor.config.onchange = (html: any) => {
  42. this.valueChange.emit(html)
  43. if (this.onChange) {
  44. this.onChange(html);
  45. }
  46. }
  47. this.wangEditor.config.onchangeTimeout = 500;
  48. this.wangEditor.create();
  49. this.wangEditor.txt.html(this.html)
  50. }, 200);
  51. }
  52. }

大致思路:

  • 使用ViewChild引用html的dom元素
  • 在OnInit的成功後,初始化WangEditor編輯器,把模板中的ElementRef放入到WangEditor的容器中去,讓WangEditor去控制介面的dom操作。
  • 實現ControlValueAccessor,讓這個元件支援Angular的表單驗證。
  • 實現ngOnDestroy,元件在銷燬的時候,呼叫WangEditor的destory

4.使用元件

  1. <q-wang-editor [height]="550"></q-wang-editor>

5.效果預覽

6.最後

一個WangEditor的Angular元件封裝就基本完成了。如果需要更多功能,比如圖片上傳,等可以再根據自己的需求增加功能即可


歡迎大家關注我的公眾號【青城同學】和我交流