Intergrate vscode editor in angular

To intergrate vscode editor in angular 13 typescript and above, ngx monaco editor should be installed. The following steps described how to install and setup it.

1, Install ngx-monaco-editor js packages

 npm install monaco-editor ngx-monaco-editor --save

2, Add the glob to assets in angular.json schema – projects.[project-name].architect.build (to make monaco-editor lib available to the app):

{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "version": 1,
  "newProjectRoot": "projects",
  "projects": {
    "projectName": {
      "projectType": "application",
      "schematics": {},
      "root": "",
      "sourceRoot": "src",
      "prefix": "app",
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "dist/open-ai",
            "index": "src/index.html",
            "main": "src/main.ts",
            "polyfills": [
              "zone.js"
            ],
            "tsConfig": "tsconfig.app.json",
            "assets": [
              "src/favicon.ico",
              "src/assets",
              { "glob": "**/*", "input": "node_modules/monaco-editor", "output": "assets/monaco-editor" }
            ],
            "styles": [
              "src/assets/styles/app.scss"
            ],
            "scripts": []
          },

3, In app.module or your sub-module ts file, and editor config, define NgxMonacoEditorConfig

import {MonacoEditorModule, NgxMonacoEditorConfig} from "ngx-monaco-editor";


const monacoConfig: NgxMonacoEditorConfig = {
  baseUrl: '/assets', // configure base path cotaining monaco-editor directory after build default: './assets'
  defaultOptions: { scrollBeyondLastLine: false }, // pass default options to be used
  onMonacoLoad: () => { console.log((<any>window).monaco); } // here monaco object will be available as window.monaco use this function to extend monaco editor functionalities.
};

@NgModule({
  declarations: [
  ],
  imports: [
    MonacoEditorModule.forRoot(monacoConfig),
  ]
})
export class CodeModule { }

4, in your component.html file, add ngx-monaco-editor,

  <ngx-monaco-editor class="full-height" #codeContainer [options]="editorOptions" [(ngModel)]="code"></ngx-monaco-editor>

define options in components.ts file

  editorOptions = {theme: 'vs-dark', language: 'javascript'};
  code: string= 'function x() {\nconsole.log("Hello world!");\n}';

5, restart your application

Leave a Reply

Your email address will not be published. Required fields are marked *