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

在Ace编辑器中高亮整行:Angular只读JSON场景的实现需求

在Angular中实现Ace编辑器高亮包含特定字符串的整行

1. 安装依赖

先确保项目引入Ace编辑器相关依赖:

npm install ace-builds @types/ace --save

2. 组件中配置Ace编辑器

在组件TS文件中初始化编辑器,设置只读模式并实现高亮逻辑:

import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
import * as ace from 'ace-builds';

@Component({
  selector: 'app-json-viewer',
  templateUrl: './json-viewer.component.html',
  styleUrls: ['./json-viewer.component.css']
})
export class JsonViewerComponent implements OnInit {
  @ViewChild('aceEditor') aceEditorRef!: ElementRef<HTMLElement>;
  private editor!: ace.Ace.Editor;
  targetString = '特定字符串'; // 替换为你需要匹配的目标字符串

  ngOnInit(): void {
    // 初始化编辑器
    this.editor = ace.edit(this.aceEditorRef.nativeElement);
    
    // 基础配置:只读模式、JSON语法高亮
    this.editor.setReadOnly(true);
    this.editor.getSession().setMode('ace/mode/json');
    this.editor.setTheme('ace/theme/github'); // 可选,根据项目需求更换主题
    
    // 加载示例JSON数据(实际项目中替换为你的数据源)
    const jsonData = JSON.stringify({
      name: '演示数据',
      records: [
        { id: 1, desc: '包含特定字符串的行' },
        { id: 2, desc: '普通内容行' },
        { id: 3, desc: '另一行包含特定字符串' }
      ]
    }, null, 2);
    this.editor.setValue(jsonData);
    
    // 执行行高亮逻辑
    this.highlightTargetLines();
  }

  private highlightTargetLines(): void {
    const session = this.editor.getSession();
    const lineCount = session.getLength();
    
    // 清除之前的高亮标记,避免重复渲染
    session.clearMarker('target-line-highlight');
    
    // 遍历所有行,检查是否包含目标字符串
    for (let i = 0; i < lineCount; i++) {
      const lineContent = session.getLine(i);
      if (lineContent.includes(this.targetString)) {
        // 标记整行:范围覆盖当前行的起始到末尾
        const range = new ace.Range(i, 0, i, lineContent.length);
        session.addMarker(range, 'target-line-highlight', 'fullLine', true);
      }
    }
  }
}

3. 模板文件(HTML)

在组件模板中添加编辑器容器:

<div #aceEditor style="width: 100%; height: 500px;"></div>

4. 自定义高亮样式(CSS)

在组件样式文件中定义高亮行的视觉样式:

.ace_editor .target-line-highlight {
  background-color: rgba(255, 235, 59, 0.3); /* 黄色半透明背景,可根据需求调整 */
}

额外说明

  • 若目标字符串或JSON数据需要动态更新,在数据变化后重新调用highlightTargetLines()即可刷新高亮
  • 可调整样式中的颜色、透明度等参数,匹配项目UI风格
  • 若需要支持大小写不敏感匹配,将lineContent.includes(this.targetString)替换为lineContent.toLowerCase().includes(this.targetString.toLowerCase())

内容的提问来源于stack exchange,提问作者Partha Pratim Sahoo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 08:29:59