Angular 代码高亮组件

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

Github源码 欢迎你们Star😀


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

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数据结构作了一个简单的处理,后续根据具体需求会作一些扩展,欢迎你们回复。git

stackblitz
github


功能比较简单,不足之处欢迎你们批评指正😆typescript

相关文章
相关标签/搜索