ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

Angular封装WangEditor富文本组件

2021-07-29 17:32:49  阅读:271  来源: 互联网

标签:封装 WangEditor void wangEditor html editor 组件 Angular


富文本组件是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.效果预览

image

6.最后

一个WangEditor的Angular组件封装就基本完成了。如果需要更多功能,比如图片上传,等可以再根据自己的需求增加功能即可


欢迎大家关注我的公众号【青城同学】和我交流

image

标签:封装,WangEditor,void,wangEditor,html,editor,组件,Angular
来源: https://www.cnblogs.com/boxrice/p/15076158.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有