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
相关产品推荐
相关产品推荐

