angular6+codeMirror實現瀏覽器在線SQL編輯器並支持智能提示

前言:

由於我司是一個作大數據的公司,要給數據科學家們作一個在線探索數據的產品,近來有一個在線寫SQL代碼的需求。話很少說,開始:css

依賴:

    使用npm包安裝ng2-codemirror組件:node

npm install ng2-codemirror -- save

由於該組件須要codemirror,因此須要再安裝codemirror的依賴mysql

npm install codemirror -- save

好啦,全部的依賴都裝好了。sql

使用:

在須要使用的組件的module中引入ng2-codemirror:npm

import { CodemirrorModule } from 'ng2-codemirror';
@NgModule({
  imports: [
    CodemirrorModule
  ]
})

接下來就能夠在組件中直接使用codemirror了!json

import { Component } from 'angular2/core';

@Component({
  selector: 'sample',
  template: `
    <codemirror [(ngModel)]="code"
      [config]="cmOptions">
    </codemirror>
  `
})

export class Sample{
  constructor(){
   private code: any = '';
   private cmOptions: any = '';
  }
}

至此,codemirror就算集成到angular中了。可是,你會發現一個問題,codemirror的樣式不見啦!!!這可咋辦,別急,咱們須要引入codemirror的css文件。可是此時又發現無法直接在ts文件中引入node_module中的css文件。angular2

因此我選擇在在根目錄的angular.json做爲靜態資源引入全局。大數據

"styles": [
  "node_modules/codemirror/lib/codemirror.css"
]

引入完以後發現,納尼,怎麼不起做用。仔細一想,引入靜態資源須要重跑項目。項目重跑以後發現,OK了。接下來就須要支持sql輸入。this

咱們在使用codemirror的組件中引入:spa

import * as CodeMirror from 'codemirror';
import 'codemirror/mode/sql/sql';
import 'codemirror/addon/hint/show-hint.js';
import 'codemirror/addon/hint/sql-hint.js';

而後將codemirror的參數加上:

export class Sample{ 
   constructor(){ 
    private code: any = '';
    private cmOptions: any = {
      lineNumbers: true,                     //顯示行號
      mode: { name: "text/x-mysql" },          //定義mode
      extraKeys: {
        "'a'": this.completeAfter,
        "'b'": this.completeAfter,
        "'c'": this.completeAfter,
        "'d'": this.completeAfter,
        "'e'": this.completeAfter,
        "'f'": this.completeAfter,
        "'g'": this.completeAfter,
        "'h'": this.completeAfter,
        "'i'": this.completeAfter,
        "'j'": this.completeAfter,
        "'k'": this.completeAfter,
        "'l'": this.completeAfter,
        "'m'": this.completeAfter,
        "'n'": this.completeAfter,
        "'o'": this.completeAfter,
        "'p'": this.completeAfter,
        "'q'": this.completeAfter,
        "'r'": this.completeAfter,
        "'s'": this.completeAfter,
        "'t'": this.completeAfter,
        "'u'": this.completeAfter,
        "'v'": this.completeAfter,
        "'w'": this.completeAfter,
        "'x'": this.completeAfter,
        "'y'": this.completeAfter,
        "'z'": this.completeAfter,
        "'.'": this.completeAfter,
        // "'='": this.completeIfInTag,
        "Ctrl-Enter": "autocomplete",
        Tab: function (cm) {
          var spaces = Array(cm.getOption("indentUnit") + 1).join(" ");
          cm.replaceSelection(spaces);
        }
      },   //自動提示配置
    };
  } 
}

好了,此時就能夠愉快的寫SQL了。還支持智能提示喲,支持回車鍵 和 TAB鍵。下面貼出效果圖:

 

-------END-------

相關文章
相關標籤/搜索