AngularはWangEditorリッチテキストコンポーネントをカプセル化します

リッチテキストコンポーネントは、特にブログやフォーラムなどのWebサイトの背景を開発するために、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.2tsロジック

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のdestroyを呼び出します。

4.コンポーネントを使用する

<q-wang-editor [height]="550"></q-wang-editor>	
复制代码

5.エフェクトプレビュー

画像

6.最後に

WangEditorのAngularコンポーネントのカプセル化は基本的に完了しています。画像のアップロードなど、さらに機能が必要な場合は、必要に応じて機能を追加できます。


私のパブリックアカウント[Qingchengクラスメート]に注意を払い、私とコミュニケーションをとってください。

おすすめ

転載: juejin.im/post/6990276608666009614