MathJax 未定义角度 4

问题描述 投票:0回答:2

我已经运行命令 npm install mathjax 和 npm install --save @types/mathjax

并在 angular-cli.json 中添加了 mathjax.js 的引用

"../node_modules/mathjax/mathjax.js?config=TeX-AMS-MML_HTMLorMML"

。我已经创建了指令

import { Directive, Input, OnChanges, ElementRef } from '@angular/core';
    declare var MathJax: any;

    @Directive({
    selector: '[MathJax]'
    })
    export class MathJaxDirective implements OnChanges {

        @Input('MathJax') private value: string;

        constructor(private element: ElementRef) {

    }

    ngOnChanges() {

        // console.log('- onChange -');
        // console.log(this.value);

        this.element.nativeElement.innerHTML = this.value;
        MathJax.Hub.Queue(["Typeset", MathJax.Hub, this.element.nativeElement]);
        }

    }

这显示错误 Mathjax ReferenceError:MathJax 未定义

我在 tsconfig.app.json 类型中添加了 mathjax

        {
      "extends": "../tsconfig.json",
      "compilerOptions": {
        "outDir": "../out-tsc/app",
        "baseUrl": "./",
        "module": "es2015",
        "types": [
          "mathjax"
        ]
      },
      "exclude": [
        "test.ts",
        "**/*.spec.ts"
      ]
    }       
angular mathjax
2个回答
0
投票

您收到 MathJax“未定义”,因为它未加载到您的浏览器。 要么添加

 <script type="text/javascript" async
  src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS_CHTML">
</script>

或更换

declare var MathJax: any;

import { MathJax } from 'mathjax';

并将“mathjax”添加到 src/tsconfig.app.json 中的 types 数组中。


0
投票

基于此演示https://mathjax.github.io/MathJax-demos-web/input-tex2chtml.html.html您可以尝试像这样更改代码:

ngOnChanges() {
  this.target = this.element.nativeElement;
  MathJax.texReset();
  const options = MathJax.getMetricsFor(this.target);
  const node = await MathJax.tex2chtmlPromise(this.value, options);
  this.target.parentElement?.appendChild(node);
  this.target.style.display = 'none';
  MathJax.startup.document.clear();
  MathJax.startup.document.updateDocument();
}

正如 @Sundar 提到的,请确保在您的

index.html
中包含 mathjax 脚本标记,现在看起来像这样:

<script id="MathJax-script" async
  src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js">
</script>
© www.soinside.com 2019 - 2024. All rights reserved.