Angular 代码高亮组件

最近公司在考虑开源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


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



本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部