富文本组件是web程序中很经常使用的一个组件,特别是要开发一个博客,论坛这类的网站后台。css
得益于Angular的强大,封装WangEditor组件很是简单html
yarn add wangeditor
ng g c q-wang-editor
<div #wang></div>
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); } }
大体思路:node
<q-wang-editor [height]="550"></q-wang-editor>
一个WangEditor的Angular组件封装就基本完成了。若是须要更多功能,好比图片上传,等能够再根据本身的需求增长功能便可web
欢迎你们关注个人公众号【青城同窗】和我交流typescript