如何在Angular全项目配置MathJax支持反引号分隔的AsciiMath
Angular 配置 MathJax 识别反引号包裹的 AsciiMath 公式
1. 根模块配置(app.module.ts)
在根模块中通过 MathjaxModule.forRoot 完成核心配置,指定加载 AsciiMath 输入器、输出器,并将反引号设为行内公式的分隔符:
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { MathjaxModule } from 'mathjax-angular'; import { AppComponent } from './app.component'; @NgModule({ declarations: [AppComponent], imports: [ BrowserModule, MathjaxModule.forRoot({ loader: { load: ['input/asciimath', 'output/chtml'] // 加载AsciiMath输入模块和CHTML输出模块 }, options: { asciimath: { inlineMath: [['`', '`']] // 配置反引号作为行内AsciiMath的识别标记 } } }) ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
2. 组件内触发渲染(按需添加)
如果公式未自动渲染,可在组件中注入 MathjaxService,在初始化阶段触发页面公式渲染:
import { Component, OnInit } from '@angular/core'; import { MathjaxService } from 'mathjax-angular'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { constructor(private mathjaxService: MathjaxService) {} ngOnInit(): void { // 触发MathJax扫描并渲染当前页面的公式 this.mathjaxService.typeset(); } }
3. 模板中使用反引号包裹 AsciiMath
在组件模板里直接用反引号包裹 AsciiMath 文本即可:
<p>行内公式示例:`sum_(i=1)^n i^3=((n(n+1))/2)^2`</p> <p>另一个示例:`int_0^1 x^2 dx = 1/3`</p>
额外注意事项
- 若需要 SVG 格式的公式输出,可将 loader 配置中的
output/chtml替换为output/svg - 如果是动态加载公式(比如异步获取数据后渲染),需在数据加载完成后再次调用
this.mathjaxService.typeset()触发重新渲染
内容的提问来源于stack exchange,提问作者K4d3
相关产品推荐
相关产品推荐

