3

Add highlight.js to an Angular 2 application

 3 years ago
source link: https://marco.dev/2017/02/13/add-highlight-js-to-an-angular-2-application/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

java-version.com: What's new in Java 16? 15? Keep up to date!

Add highlight.js to an Angular 2 application

With the goal to build my own blog application (for educational purposes) I integrated the highlight.js library in the demo application.

At the moment there are problems with safari and mobile platforms, a js error in the library.

The implementation is based on this answer in Stack Overflow (thanks to the author) 😉

In packages.json you have to import the highlight library and the type:

'highlight.js': '^9.9.0',
'@types/highlight.js': '^9.1.9',

The implementation is done via a directive:

import {Directive, ElementRef, AfterViewInit} from '@angular/core';
import * as hljs from 'highlight.js';

@Directive({
    selector: 'code[ highlight]' // css selector for the attribute
})
export class HighlightCodeDirective implements AfterViewInit{
    constructor(private eltRef:ElementRef) {
    }

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

The html code of the example:

blog_highlight_small-e1487011265898.png?resize=600%2C411

and the result:

blog_highlight_2_small-1-e1487011315602.png?resize=600%2C647

Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK