highlight.js不适用于Angular 2

时间:2016-05-18 18:53:45

标签: angular syntax-highlighting highlight.js

我正在尝试使用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/

4 个答案:

答案 0 :(得分:11)

您需要以这种方式在块上明确应用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); } }

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

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

请参阅此plunkr

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

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

并以这种方式使用它:

//Interface Library
interface INewUser {
  name: string,
  age: number,
  location: string
}

//DAL
function insertUser(data: INewUser, cb: MongoCallBack < InsertOneWriteOpResult > ) {

  //for best practices we would have an instance connected to db already
  //so we do not have to open a new connection on every request
  MongoClient.connect(uri, function(err, db) {

    //handle err first

    db.collection("users", function(err, col) {

      //handle err first

      col.insertOne(data, function(err, response: InsertOneWriteOpResult) {
        //MongoCallBack expects (MongoError, <T>) T = InsertOneWriteOpResult
        return cb(null, response)
      });

    });

  });
}


//api endpoint
app.post('/user', function(req, res) {
  //do some checks to make sure the req.body is valid -- i.e not empty no xss attacks..
  let newUser: INewUser = req.body;

  insertUser(newUser, function(err, res) {
    if (res.res.ok == 1) {
      res.json({
        success: true
      });
    }

  });
});




/*example data being posted to /user
{
  name: "test",
  age: 33,
  location: "NA"
} */

答案 1 :(得分:3)

我已经发布了 highlight.js 模块的角度,从npm安装

npm install --save ngx-highlightjs

使用非常简单,它会自动加载highlight.js并使用惰性模块,查看demo

答案 2 :(得分:2)

我认为您必须手动触发高亮显示。

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

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

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

<强> Plunker Example

答案 3 :(得分:0)

到目前为止,最好的angular的highlightjs模块是angular2-highlight-js

required dependency

npm i angular2-highlight-js