Implementing Monaco editor in Angular 18: A comprehensive guide

Incorporating the Monaco Editor into an Angular 18 project was vital for me as it allowed me to embed custom code snippets within a form, benefiting from its code suggestion feature.

Despite installing the monaco-editor npm package and setting it up in a component with the following code:

<div id="container" class="h-[50vh]"></div>
import { Component } from '@angular/core';
import * as monaco from 'monaco-editor/esm/vs/editor/editor.api';

@Component({
  selector: 'app-code-editor',
  templateUrl: './code-editor.component.html',
  styleUrl: './code-editor.component.scss',
})
export class CodeEditorComponent {
  ngAfterViewInit() {
    self.MonacoEnvironment = {
      getWorkerUrl: function (moduleId, label) {
        if (label === 'json') {
          return './vs/language/json/json.worker.js';
        }
        if (label === 'css' || label === 'scss' || label === 'less') {
          return './vs/language/css/css.worker.js';
        }
        if (label === 'html' || label === 'handlebars' || label === 'razor') {
          return './vs/language/html/html.worker.js';
        }
        if (label === 'typescript' || label === 'javascript') {
          return './vs/language/typescript/ts.worker.js';
        }
        return './vs/editor/editor.worker.js';
      },
    };

    const element = document.getElementById('container');
    if (element) {
      monaco.editor.create(element, {
        value: ['function x() {', '\tconsole.log("Hello world!");', '}'].join(
          '\n',
        ),
        language: 'javascript',
      });
    }
  }
}

The setup allowed me to view and write code within the editor window, though the full functionality of Monaco was not operational. Features like accessing commands by pressing F1, code highlighting, and suggestions were non-functional.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to turn off the "defer" feature in an Angular build?

After compiling my Angular project, I noticed that the compiler automatically adds the "defer" attribute to the script tag in my "index.html" file. However, I need to disable this feature. Is there a way to do it? I am currently working with Angular versi ...

Updating the value of a radio button prior to triggering the click event

I am facing an issue with click events on my radio buttons. The validators are being set or cleared before the value actually changes. When the Yes radio button is clicked, I want to toggle the validators for the additional field that it reveals. If the N ...

When attempting to use a context, the type '...' cannot be assigned to type '...'

In my Next.js project, I am utilizing createContext to implement a dark mode button. The original jsx file for this functionality is called ThemeContext.tsx, and I am currently in the process of converting it to TypeScript. "use client"; import ...

What impact does the size of the unpacked files have on the overall minified size of an npm package?

I've been working on shrinking the size of an npm package I created, and I've successfully reduced the unpacked size to around 210kb. https://www.npmjs.com/package/@agile-ts/core/v/0.0.12 <- 210kb https://www.npmjs.com/package/@agile-ts/core ...

What is the reason for TypeScript resolving this type union as an intersection?

I'm struggling to grasp the logic behind a typescript error that keeps popping up - it feels like there's a fundamental concept swiftly flying over my head, making a "whoosh" sound as it goes by. I stumbled upon this discussion about a similar e ...

Guide to asynchronously loading images with Bearer Authorization in Angular 2 using NPM

I am in search of a recent solution that utilizes Angular2 for my image list. In the template, I have the following: <div *ngFor="let myImg of myImages"> <img src="{{myImg}}" /> </div> The images are stored as an array w ...

Slider in Angular Material not moving along the track

When I attempt to slide the mat-slider control using the mouse, it doesn't move left or right. Instead, it only responds when I click on a specific point along the sliding line. Here is the code snippet I am using: <div> <mat-slider>& ...

What is the best way to loop through an array of objects or transform a list of objects into an array?

When I make a call to the SQL Server API, I receive a response in the following structure: { "recordsets": [ [ { "id_alquiler": 71735, "nombre_tipo_exhibidor": "Exhibidores de Temporada", "nombre_empresa": "TIOMAE", ...

Ways to verify if Angular application is operating in cloud mode

In the process of developing an Angular application, I am facing the challenge of identifying whether the app is operating in a cloud environment. Is there a way to programmatically determine this within the Angular codebase? Are there any specialized Angu ...

Angular's HttpClient.get method seems to have trouble retrieving real-time data from a Firebase database

I have been debugging and I suspect that the error lies in this part of the code. The DataService class's cargarPersonas function returns an Observable object, but I am struggling to understand how to properly retrieve the database data and display it ...

The Amadeus flight booking feature is running smoothly, however, the Hotel Booking API is not functioning properly

When I initially integrated Amadeus for flight booking, everything worked smoothly. However, issues arose when trying to integrate hotel bookings. When utilizing the nodejs library of Amadeus for hotel offers, an error was encountered stating that the acce ...

Sharing component controllers in Angular2 allows for better organization and reuse of

My dilemma involves two separate page components, Services and Users, that share almost identical methods except for the type classes they use. The templates for both components are similar, but they display different class properties. It feels redundant t ...

What is the best way to categorize array items based on a specific TypeScript type?

Imagine having the following data array: const information = [ { group: 'z', name: 'hello' }, { group: 'z', name: 'hello2' }, { group: 'z', name: 'hello3' }, { group: 'x&apo ...

Exploring Mikro-ORM with Ben Awad's Lireddit: Navigating the Process of Running Initial Migrations

Having some trouble following the lireddit tutorial, particularly with the initial mikro-orm migration step. Encountering a similar issue as mentioned in this post. Tried modifying the constructor of the example entity (tried both provided format and the ...

Problem with Ionic 2 local storage: struggling to store retrieved value in a variable

Struggling to assign the retrieved value from a .get function to a variable declared outside of it. var dt; //fetching data this.local.get('didTutorial').then((value) => { alert(value); dt = value; }) console.log("Local Storage value: " ...

Is there a way to manage specific HTML elements in Angular?

I am working on displaying a list of enable/disable buttons for different users. The goal is to show the appropriate button for each user based on their status - enabling if disabled and disabling if enabled. To achieve this, I have utilized the flags "use ...

What causes data to be emitted sporadically by a subject?

We are seeking your input. Within the constructor of the component, there is code that listens for the mode which enables the isReportMode$ report from the service. However, upon switching to another component and returning back, the isReportMode$ variab ...

What is the best way to receive a notification once the final observable has completed emitting its values?

In the past, we only made one call to the API reqFinanceDataWithFilters(req): Observable<any> { return this.http.post(env.baseUrl + req.url, req.filters) .pipe(map(this.extractResults)); } However, the response from this single request was a ...

Positioning of SVG text along the y-axis

https://i.sstatic.net/FkBRo.png In my project, I am creating a population pyramid using d3 in combination with react. While d3 handles the calculations, react is responsible for rendering the DOM elements. Everything is going smoothly so far, except for p ...

Transforming a typical JSON file into a parent-child hierarchical JSON structure similar to the one utilized in d3's flare.json file format

My JSON file has a specific structure: { "a": "b", "c": "d", "e": { "f": "g", "h": "i" } } I want to transform it into the following structure: { "name": "Root", "parent": "null", "children": [ { ...