angular 12 显示数学公式

Fork Me On Github

angular 12 显示数学公式

公式的格式

主要有两种写法格式:

  1. LaTeX
  2. AsciiMath

安装依赖

这里使用的是 KaTeX,默认支持 LaTeX,如果需要支持 AsciiMath 则需要 安装转化工具 asciimath2tex

npm i katex

npm i asciimath2tex

默认是有 angular 版本的 KaTeX


npm i ng-katex

注意

ng-katex 默认根据 $$$ 来识别处理公式的

例如

$a=x^2$

代码

但是我不知需要显示公式,还需要处理一些其他的,所以直接使用 KaTeX 进行处理

npm i katex

npm i asciimath2tex
import * as katex from 'katex';
import AsciiMathParser from 'asciimath2tex';

    private formatContent() {
        const items: IMarkItem[] = [];
        const content = this.content.trim();
        let index = -1;
        let start = 0;
        const parser = new AsciiMathParser();
        const pushMath = () => {
            index ++;
            start = index;
            while (index < content.length - 1) {
                if (content.charAt(++index) === '$'  && backslashedCount(index - 1) % 2 === 0) {
                    break;
                }
            }
            items.push({
                type: 'math',
                content: this.sanitizer.bypassSecurityTrustHtml(
                    katex.renderToString(parser.parse(content.substring(start, index)))
                )
            });
        };
        const pushText = (end: number) => {
            if (end > content.length) {
                end = content.length;
            }
            if (start >= end) {
                return;
            }
            const text = content.substring(start, end);
            if (text.length < 1) {
                return;
            }
            items.push({
                type: 'text',
                content: text,
            });
        };
        const backslashedCount = (i: number) => {
            let count = 0;
            while (i >= 0) {
                if (content.charAt(i --) === '\\') {
                    count ++;
                    continue;
                }
                break;
            }
            return count;
        };

        while (index < content.length - 1) {
            const code = content.charAt(++index);
            if (code === '$' && backslashedCount(index - 1) % 2 === 0) {
                pushText(index);
                pushMath();
                start = index + 1;
                continue;
            }
            if (code === '\n') {
                pushText(index);
                items.push({
                    type: 'line',
                });
                start = index + 1;
                continue;
            }
        }
        pushText(index + 1);
        this.items = items;
    }

关键代码

import * as katex from 'katex';
import AsciiMathParser from 'asciimath2tex';

katex.renderToString(parser.parse(content));

根据提取的公式转化成 html 代码

Click here to view
Tags: angular
0 343 0
在 angular 项目中实现对页面的访问控制
按下回车键,焦点移动到下一个表单或提交表单
使用ng-template 显示tree结构数据
使用 ViewContainerRef.createComponent 替代 ComponentFactoryResolver
ng-deep 使用