El componente de texto enriquecido es un componente muy utilizado en programas web, especialmente para desarrollar un fondo de sitio web como un blog y un foro.
Gracias al poder de Angular, es muy simple encapsular el componente WangEditor
1. Instale wangeditor usando yarn o npm
yarn add wangeditor
复制代码
2. Crea un componente Angular
ng g c q-wang-editor
复制代码
3. Encapsular la lógica de los componentes
3.1 Plantilla
<div #wang></div>
复制代码
3.2 ts lógica
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);
}
}
复制代码
Idea general:
- Use ViewChild para hacer referencia al elemento dom de html
- Después del éxito de OnInit, inicialice el editor WangEditor, coloque ElementRef en la plantilla en el contenedor de WangEditor y deje que WangEditor controle la operación dom de la interfaz.
- Implemente ControlValueAccessor para que este componente admita la validación de formularios de Angular.
- Implemente ngOnDestroy, cuando se destruya el componente, llame a la destrucción de WangEditor
4. Usar componentes
<q-wang-editor [height]="550"></q-wang-editor>
复制代码
5. Vista previa del efecto
6. Finalmente
Una encapsulación de componentes angulares de WangEditor está básicamente completada. Si necesita más funciones, como la carga de imágenes, puede agregar funciones según sus propias necesidades.
Bienvenidos a todos a prestar atención a mi cuenta pública [compañeros de clase de Qingcheng] y comunicarse conmigo