highlight.js不能与Angular 2配合使用。

12
我正在尝试使用highlight.js为应用添加语法高亮,但它似乎无法与Angular 2一起使用。
请问我可能做错了什么?
这是Plnkr链接:https://plnkr.co/edit/G3NFFPGXKyc9mV1a6ufJ?p=preview 这是组件内容:
import {Component} from 'angular2/core';
@Component({
selector: "my-app",
template: `
Hello!
<pre>
            <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{
}
这是我使用CDN添加highlight.js的地方:
<!DOCTYPE html>
<html>
   <head>
      <!-- IE required polyfills, in this exact order -->
      <script src="https://cdnjs.cloudflare.com/ajax/libs/es6-shim/0.35.0/es6-shim.js"></script>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.25/system-polyfills.js"></script>
      <script src="https://npmcdn.com/angular2/es6/dev/src/testing/shims_for_IE.js"></script>
      <!-- Angular polyfill required everywhere -->
      <script src="https://code.angularjs.org/2.0.0-beta.13/angular2-polyfills.js"></script>
      <script src="https://code.angularjs.org/tools/system.js"></script>
      <script src="https://code.angularjs.org/tools/typescript.js"></script>
      <script src="https://code.angularjs.org/2.0.0-beta.13/Rx.js"></script>
      <script src="https://code.angularjs.org/2.0.0-beta.13/angular2.dev.js"></script>
      <link rel="stylesheet" href="style.css" />
      <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.4.0/styles/solarized-light.min.css">
      <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.4.0/highlight.min.js"></script>
      <script>hljs.initHighlightingOnLoad();</script>
      <script>
         System.config({
           transpiler: 'typescript', 
           typescriptOptions: { emitDecoratorMetadata: true }, 
           packages: {
             'api': {defaultExtension: 'ts'}, 
             'app': {defaultExtension: 'ts'} 
           } 
         });
         System.import('app/main')
             .then(null, console.error.bind(console));
      </script>
   </head>
   <body>
      <my-app>loading...</my-app>
   </body>
</html>

https://highlightjs.org/usage/


很棒的代码高亮文章 https://blog.almightytricks.com/2020/10/27/code-highlighting-ngx-quill/ - Sangram Badi
5个回答

19

你需要明确地在代码块上应用highlightjs,方式如下:

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);
  }
}

请参考这个 plunkr

一个好的方法是为此创建一个自定义指令:

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

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

然后这样使用它:

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

2
谢谢 Thierry。 它可以工作。 但是如果在同一页上有多个代码块怎么办? 我能将 #code 应用于所有这些块吗? 我以为我只能在一个块上使用 #code。 - takeradi
不客气!是的,你说得对;-) 我添加了一个基于指令的方法。请查看我的更新答案... - Thierry Templier
谢谢,使用指令的解决方案非常好! - Koraxos

6
我已经为Angular发布了highlight.js模块,可以从npm安装。
npm install --save ngx-highlightjs

使用它非常简单,它会自动为您加载highlight.js,并与懒加载模块兼容,请查看演示


@PSKP 我已经更新了链接 https://ngx-highlight.netlify.app/ - Murhaf Sousli

4

我认为你需要手动触发高亮。

你可以将此功能委托给特殊指令,如:

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

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

Plunker示例 点击此处查看Plunker示例。

当在 ngAfterViewInit() 中调用 highlightBlock 方法时,它可以在页面上的多个预格式标签上工作。请查看Thierry的解决方案,并尽可能给他的答案点赞。 - takeradi
@mila 谢谢。已修复。 - yurzui

3

Angular 12+

另一种做法是使用highlight.js的自定义用法

首先,安装该库

 npm install highlight.js

将样式文件添加到angular.json


"styles": [
   "./node_modules/highlight.js/styles/default.css" // I choose default but you can choose your favorite one.
],

在组件中,您想要使用高亮器,请导入highlight.js。
import hljs from 'highlight.js';

...

 constructor(@Inject(DOCUMENT) private document: Document) { }

 ngOnInit(): void {
    setTimeout(() => {
          this.document.querySelectorAll('pre code').forEach((el) => {
            hljs.highlightElement(el);
          });
        }, 500)
  }

注意:如果你从 API 获取数据,请确保数据在页面上呈现,然后再运行 forEach()。


0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接