AngularJS集成wangeditor富文本編輯器

最近用AngularJS2(ng alain)搭建的項目需求中須要富文本,在網上找了不少,要麼過重,要麼沒有詳細的集成步驟。css

下面將我本身如何將wangeditor集成在項目(項目名稱myPro)中的,詳細列出。html

具體操做步驟

操做步驟參考:node

https://github.com/fengnovo/wangEditor/tree/master/example/demo/in-ng2git

編輯器操做參考文檔:github

https://www.kancloud.cn/wangfupeng/wangeditor2/113969npm

可是仍是沒起來,控制檯報錯,找不到元素。只能本身修改了。json

(1)安裝wangeditor

項目跑起來以後,安裝wangeditor。須要加版本安裝,我目前用的是2.1.23,不知道爲啥,安裝其餘版本仍是會報錯,目前沒找到緣由。app

// 安裝命令

npm install wangeditor@2.1.23 --save

(2)修改tsconfig.json文件

myPro/tsconfig.json文件,這是最終的代碼。less

{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "module": "es2015",
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es5",
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2017",
      "dom"
    ],
    // wangeditor
    "allowJs": true,
    "mapRoot": "./"
  }
}

(3)添加editor模板

myPro/src/app下面添加editor模板,專門來測試這個功能。這是個人一個習慣,先弄一個獨立的文件測試好功能,而後再把他放在項目中應用。dom

cd到myPro/src/app文件下面

// 命令生成模板

ng generate component editor

(4)myPro/src/app/editor/editor.component.html

<nz-layout style="padding:24px 0;">
  <div style="background-color: white; padding: 24px;">
    <div id="editorElem" style="height: 400px;">
      <p>請輸入內容...</p>
    </div>

    <button (click)="getVal()" style="margin-top: 10px;">獲取內容</button>

  </div>
</nz-layout>

(5)myPro/src/app/editor/editor.component.ts

import {Component, OnInit, ElementRef, Renderer, Output, EventEmitter } from '@angular/core';
import * as wangEditor from '../../../node_modules/wangeditor/dist/js/wangEditor.js';


@Component({
  selector: 'app-editor',
  templateUrl: './editor.component.html',
  styleUrls: ['./editor.component.css']
})
export class EditorComponent implements OnInit {

  private editor: any
  @Output() onPostData = new EventEmitter()

  constructor(private el: ElementRef, private renderer: Renderer) { }

  ngOnInit() {
 	 // 以防元素獲取不到
  	setTimeout(function() {
      const editordom = document.querySelector('#editorElem');
      console.log(editordom);
      if(editordom) {
        this.editor = new wangEditor(editordom)
        // 上傳圖片
        this.editor.config.uploadImgUrl = '/upload';
        this.editor.create();
      }
    }, 0)
  }

  getVal(): any {
    console.log(this.editor)
    console.log(this.editor.$txt)
    const data = this.editor.$txt.text();
    const data1 = this.editor.$txt.html();
    console.log(data);
    console.log(data1);
  }

}

(6)myPro/src/style.css或者myPro/src/style.less

/* You can add global styles to this file, and also import other style files */
@import "~wangeditor/dist/css/wangEditor.min.css";

PS: 以上代碼都是最終代碼,按照這樣的步驟將wangeditor集成在AngularJS2的項目中,目前好用。

相關文章
相關標籤/搜索