You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Monaco Editor及ngx-monaco-editor如何为指定词汇添加高亮及点击回调

适配ngx-monaco-editor的词汇高亮与点击回调实现方案

1. 基础配置(模板与变量定义)

首先在Angular组件模板中绑定编辑器初始化事件,获取Monaco实例:

<!-- 组件模板 -->
<ngx-monaco-editor 
  [options]="editorOptions" 
  [(ngModel)]="javaCode" 
  (editorInit)="onEditorInit($event)"
  style="height: 600px;"
>
</ngx-monaco-editor>

组件内定义基础变量:

// 组件类变量
editor: any;
// 存储高亮装饰的ID,用于后续更新/清除
decorationIds: string[] = [];
// 自定义高亮词汇配置,可绑定对应回调
highlightConfigs = [
  {
    word: 'HashMap',
    clickCallback: () => alert('点击了HashMap,可跳转定义/展示详情')
  },
  {
    word: 'ArrayList',
    clickCallback: () => console.log('触发ArrayList的自定义逻辑')
  }
];
// 编辑器基础配置
editorOptions = {
  theme: 'vs',
  language: 'java',
  readOnly: false
};
javaCode = `public class Test {
  public static void main(String[] args) {
    HashMap<String, Object> map = new HashMap<>();
    ArrayList<String> list = new ArrayList<>();
  }
}`;

2. 词汇高亮实现

通过deltaDecorations实现自定义高亮,给高亮元素添加专属类名用于后续识别:

// 高亮指定词汇方法
refreshHighlight() {
  if (!this.editor) return;
  const model = this.editor.getModel();
  const codeContent = model.getValue();
  const newDecorations: any[] = [];

  // 先清除旧的高亮装饰
  this.decorationIds = this.editor.deltaDecorations(this.decorationIds, []);

  this.highlightConfigs.forEach(config => {
    // 特殊字符转义,全词匹配规则可按需调整
    const escapedWord = config.word.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
    const wordRegex = new RegExp(`\\b${escapedWord}\\b`, 'g');
    let matchResult: RegExpExecArray | null;

    while ((matchResult = wordRegex.exec(codeContent)) !== null) {
      // 计算匹配词汇的位置范围
      const startPos = model.getPositionAt(matchResult.index);
      const endPos = model.getPositionAt(matchResult.index + config.word.length);
      newDecorations.push({
        range: new monaco.Range(
          startPos.lineNumber,
          startPos.column,
          endPos.lineNumber,
          endPos.column
        ),
        options: {
          // 自定义类名,用于样式控制和点击识别
          className: 'custom-word-highlight',
          isWholeLine: false
        }
      });
    }
  });
  // 添加新高亮并存储ID
  this.decorationIds = this.editor.deltaDecorations([], newDecorations);
}

添加高亮样式:

/* 全局样式文件中添加,或组件关闭视图封装后添加 */
.custom-word-highlight {
  background-color: #fff266 !important;
  border-radius: 3px;
  cursor: pointer !important;
}

3. 高亮元素点击事件绑定

在编辑器初始化完成后,监听鼠标点击事件,识别点击位置是否为自定义高亮元素,触发对应回调:

// 编辑器初始化回调
onEditorInit(editorInstance: any) {
  this.editor = editorInstance;
  // 先执行一次高亮
  this.refreshHighlight();

  // 绑定点击事件监听
  this.editor.onMouseDown((event: any) => {
    // 仅处理内容文本区域的点击
    if (event.target.type !== monaco.editor.MouseTargetType.CONTENT_TEXT) return;
    const clickPos = event.target.position;
    // 获取点击行的所有装饰
    const lineDecorations = this.editor.getLineDecorations(clickPos.lineNumber);
    // 匹配自定义高亮装饰
    const targetDeco = lineDecorations.find((deco: any) => {
      return deco.options.className === 'custom-word-highlight' && deco.range.containsPosition(clickPos);
    });
    if (targetDeco) {
      // 获取点击的词汇内容
      const clickWord = this.editor.getModel().getWordAtPosition(clickPos)?.word;
      // 匹配配置触发对应回调
      const targetConfig = this.highlightConfigs.find(item => item.word === clickWord);
      targetConfig?.clickCallback();
    }
  });

  // 可选:代码内容变更时自动刷新高亮
  this.editor.onDidChangeModelContent(() => {
    this.refreshHighlight();
  });
}

可选调整点

  • 正则匹配可去掉\b边界符实现非全词匹配
  • 可在highlightConfigs中扩展参数,给回调传递词汇位置、上下文等信息
  • 高亮样式可修改custom-word-highlight类实现下划线、字体颜色变化等效果

内容的提问来源于stack exchange,提问作者user3006967

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 07:09:00