Search code examples
javascriptangularelectroncodemirror

How to apply text alignment to a paragraph in Codemirror on Angular?


In HTML:

<codemirror 
 [(ngModel)]="chaptersService.currentChapter.novel" 
 [config]="{
  lineWrapping: true, 
  autofocus: true, 
  showCursorWhenSelecting: true
 }"
 #novelEditor>
</codemirror>

In component.ts:

import { CodemirrorComponent } from 'ng2-codemirror';
...
@ViewChild('novelEditor') private novelEditor: CodemirrorComponent;
...
setTextCenter() {
 const cm = this.novelEditor.instance;
 const num = cm.getCursor().line;
 const lineHandle = cm.getLineHandle(num);
 cm.markText(
  {line: num, ch: 0},
  {line: num, ch: lineHandle.styles[1]},
  { css: 'text-align: center'}
 );
 this.refreshCodemirror();
}

I get such a result: enter image description here

I need to apply style for CodeMirror-line. Are there any other ways to implement this?


Solution

  • I solved this problem in this way

    setTextLeft() {
     const cm = this.novelEditor.instance;
     const num = cm.getCursor().line;
     cm.removeLineClass(num,'text');
     cm.addLineClass(num, 'text', 'lineTextLeft');
     this.refreshCodemirror();
    }
    setTextCenter() {
     const cm = this.novelEditor.instance;
     const num = cm.getCursor().line;
     cm.removeLineClass(num,'text');
     cm.addLineClass(num, 'text', 'lineTextCenter');
     this.refreshCodemirror();
    }
    setTextRight() {
     const cm = this.novelEditor.instance;
     const num = cm.getCursor().line;
     cm.removeLineClass(num,'text');
     cm.addLineClass(num, 'text', 'lineTextRight');    
     this.refreshCodemirror();
    }
    

    And scss:

    .CodeMirror-line {
      &.lineTextLeft {
        text-align: left;
      }
      &.lineTextCenter {
        text-align: center;
      }
      &.lineTextRight {
        text-align: right;
      }
    }