highlight.js does not work with Angular 2

☆樱花仙子☆ 提交于 2019-11-30 19:33:34
Thierry Templier

You need to explicitly apply highlightjs on a block this way:

import {Component, ElementRef, ViewChild} from 'angular2/core';

declare var hljs: any;

@Component({
  selector: "my-app",
  template: `
    Hello!
    <pre>
      <code #code class="html">
        &lt;html&gt;
          &lt;body&gt;

          &lt;h1&gt;My First Heading&lt;/h1&gt;
          &lt;p&gt;My first paragraph.&lt;/p&gt;

          &lt;/body&gt;
        &lt;/html&gt;
      </code>
    </pre>
  `
})
export class AppComponent{
  @ViewChild('code')
  codeElement: ElementRef;

  ngAfterViewInit() {
    hljs.highlightBlock(this.codeElement.nativeElement);
  }
}

See this plunkr

A good approach would be to create a custom directive for this:

@Directive({
  selector: 'code[highlight]'
})
export class HighlightCodeDirective {
  constructor(private eltRef:ElementRef) {
  }

  ngAfterViewInit() {
    hljs.highlightBlock(this.eltRef.nativeElement);
  }
}

and use it this way:

@Component({
  selector: "my-app",
  template: `
    Hello!
    <pre>
      <code highlight class="html">
        (...)
      </code>
    </pre>
  `,
  directives: [ HighlightCodeDirective ]
})
(...)

I have published highlight.js module for angular, install it from npm

npm install --save ngx-highlightjs

It is very simple to use, it loads highlight.js automatically for you and works with lazy modules, check out the demo

I think that you have to fire highlight manually.

To do that you can delegate this function to special directive like:

@Directive({
  selector: 'pre'
})
class PreHighlight implements AfterViewInit {
  constructor(private elRef: ElementRef) {}

  ngAfterViewInit() {
    hljs.highlightBlock(this.elRef.nativeElement);
  }
} 

Plunker Example

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!