Search code examples
angularcodemirror

Cannot get Codemirror HTML syntax highlighting to work in Angular 2 app


Trying to get CodeMirror's HTML highlighting to work (which as I see, has been a problem to some people as well) in my angular-cli (Angular 2 ) application.

Here's what I have:

app.component.html

<codemirror [(ngModel)]="code" [config]="config"></codemirror>
<div [innerHTML]="code"></div>

app.component.ts

export class AppComponent {
  code = `<p>My HTML</p>\n<!-- hello -->\n<p>Your HTML</p>`;

  config = {
    mode: 'htmlmixed',
    lineWrapping: false,
    lineNumbers: true,
    theme: 'monokai'
  };
}

angular-cli.json (listing the relevant section only)

"addons": [
    "../node_modules/codemirror/mode/xml/xml.js",
    "../node_modules/codemirror/mode/javascript/javascript.js",
    "../node_modules/codemirror/mode/htmlmixed/htmlmixed.js"
],

/.../

"styles": [
    "../node_modules/codemirror/lib/codemirror.css",
    "../node_modules/codemirror/theme/monokai.css"
],

app.module.ts

imports: [
    /* ... */
    CodemirrorModule,
],

I have tried various syntax patterns passing the mode as object or string, and - as you see - making sure that the xml gets loaded first. No go - the highlight is not there. I was always making sure to reboot ng serve after each edit of angular-cli.json.

Does anyone know where the problem could be buried?


Solution

  • You need to add <script src="node_modules/codemirror/lib/codemirror.js"></script> to index.html and you need to import mode you want to use in your component:

    import 'codemirror/mode/htmlmixed/htmlmixed'; <-- this
    
    export class AppComponent {
    code = `<p>My HTML</p>\n<!-- hello -->\n<p>Your HTML</p>`;
    
    config = {
      mode: 'htmlmixed',
      lineWrapping: false,
      lineNumbers: true,
      theme: 'monokai'
    };
    }