Angular 代码高亮组件

1,346 阅读1分钟

最近公司在考虑开源Angular项目涉及到的相关组件,打算做一个类似 material.angular.io 的组件demo,很多东西暂时还没有完善,目前只有一个简陋的框架,整个开源流程和机制还在分析当中,不过其中一些功能还是比较明确的,目前将其分类出来逐个实现。后续会持续更新。

Github源码 欢迎大家Star😀


具体实现是基于 highlight.js的,在外层做了一个简单的封装,源代码如下:

import {
  Component,
  OnInit,
  Input,
  OnChanges,
  ViewChild,
  ElementRef,
} from '@angular/core';
import hljs from 'highlight.js';

@Component({
  selector: 'ngx-highlight',
  templateUrl: './ngx-highlight.component.html',
  styleUrls: ['./ngx-highlight.component.scss']
})
export class NgxHighlightComponent implements OnInit, OnChanges {
  @Input()
  lang: string;
  @Input()
  code: any;

  @ViewChild('tpl')
  tpl: ElementRef;

  constructor() { }

  ngOnInit() {
    this._highlight();
  }

  ngOnChanges(changes) {
    const {
      code: {
        currentValue: code,
      },
    } = changes;

    this.code = code;
    this._highlight();
  }

  private _highlight() {
    const el = this.tpl.nativeElement as HTMLElement;

    const code = this._initCode(this.code);
    el.textContent = code;
    hljs.highlightBlock(el);
  }

  private _initCode(code) {
    let _code = '';

    switch (this.lang) {
      case 'json': {
        if (Object.prototype.toString.call(this.code) !== '[object String]') {
          _code = this._formatJson(code);
        }
        break;
      }
      default:
        _code = this.code;
        break;
    }

    return _code;
  }

  private _formatJson(json: object): string {
    return JSON.stringify(json, null, '  ');
  }
}

针对json数据结构做了一个简单的处理,后续根据具体需求会做一些扩展,欢迎大家回复。

stackblitz


功能比较简单,不足之处欢迎大家批评指正😆