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

Angular 17中如何通过函数格式化ngx-monaco-editor-v2内的JavaScript代码?

解决ngx-monaco-editor-v2的JavaScript代码格式化问题

因为ngx-monaco-editor-v2暂未内置代码格式化功能,我们可以直接调用原生monaco-editor的API实现,步骤如下:

1. 获取原生编辑器实例

通过ViewChild获取ngx-monaco-editor-v2组件,再通过其instance属性拿到原生monaco.editor.IStandaloneCodeEditor实例。同时监听编辑器的init事件,确保实例已初始化完成。

2. 实现格式化函数

利用原生monaco的format方法生成编辑操作,再通过编辑器实例的executeEdits方法应用格式化。

完整代码示例

模板文件(code-editor.component.html)

<ngx-monaco-editor-v2 
  #editor 
  [options]="editorOptions" 
  [(ngModel)]="code"
  (init)="onEditorInit()"
></ngx-monaco-editor-v2>
<button (click)="formatCode()" [disabled]="!editorReady">格式化代码</button>

组件类文件(code-editor.component.ts)

import { Component, ViewChild } from '@angular/core';
import { NgxMonacoEditorV2Component } from 'ngx-monaco-editor-v2';
import * as monaco from 'monaco-editor';

@Component({
  selector: 'app-code-editor',
  templateUrl: './code-editor.component.html',
  styleUrls: ['./code-editor.component.css']
})
export class CodeEditorComponent {
  @ViewChild('editor') editor!: NgxMonacoEditorV2Component;
  code = 'function test(){console.log("hello")}';
  editorOptions = {
    language: 'javascript',
    theme: 'vs-dark'
  };
  editorReady = false;

  onEditorInit() {
    this.editorReady = true;
  }

  formatCode() {
    if (!this.editorReady) return;

    const nativeEditor = this.editor.instance;
    const model = nativeEditor.getModel();
    if (!model) return;

    // 获取整个文档的范围
    const fullRange = model.getFullModelRange();

    // 生成格式化编辑操作
    const edits = monaco.editor.format(model, fullRange, {
      tabSize: 2,
      insertSpaces: true,
      semicolons: 'insert',
      quoteStyle: 'single'
    });

    // 应用格式化到编辑器
    nativeEditor.executeEdits('code-format', edits);
  }
}

3. 自定义格式化选项

可以根据需求调整格式化配置,常用的JavaScript格式化选项包括:

  • tabSize: 缩进空格数
  • insertSpaces: 是否使用空格代替制表符
  • semicolons: 控制分号的添加/移除/保留
  • quoteStyle: 指定引号类型(单引号/双引号)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 05:42:45