Tips for showcasing unique keywords in Ace Editor within the Angular framework

Can anyone help me with highlighting specific keywords in Angular using ace-builds? I've tried but can't seem to get it right. Here's the code snippet from my component:

Check out the code on Stackblitz

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

@Component({
 selector: 'app-root',
 templateUrl: './app.component.html',
 styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit, AfterViewInit {
 @ViewChild('editor') private editor: ElementRef;

 constructor() {}

 ngAfterViewInit() {
   ace.config.set('fontSize', '14px');
   const editor = ace.edit(this.editor.nativeElement);
   const oop = ace.require('ace/lib/oop');
   const TextMode = ace.require('arc/mode/text').Mode;
   const TextHighlightRules = ace.require(
     'ace/mode/text_highlight_rules'
   ).TextHighlightRules;

   const customHighlightRules = function () {this.$rules = {start: [{regex: /\b(keyword1|keyword2)\b/,token: 'keyword'}]};};

   oop.inherits(customHighlightRules, TextHighlightRules);

   const Mode = function () { this.HighlightRules = customHighlightRules; };

   oop.inherits(Mode, TextMode);

   (function () { this.$id = 'ace/mode/custom'; }.call(Mode.prototype));

   // Set here
   editor.getSession().setMode(new (ace.require('ace/mode/custom').Mode)());
   
   editor.setValue('keyword1 some text keyword2', 1);
 }

 ngOnInit() {}
}

Answer №2

Give this a try, and ensure that the specified keywords are included in the list

import { Component, OnInit, AfterViewInit, ViewChild, ElementRef } from '@angular/core';

declare var ace: any; // Include the ace library (ensure it's properly installed)

@Component({
  selector: 'app-ace-builds-editor',
  templateUrl: './ace-builds-editor.component.html',
  styleUrls: ['./ace-builds-editor.component.css']
})
export class AceBuildsEditorComponent implements OnInit, AfterViewInit {
  @ViewChild("editor") private editor: ElementRef<HTMLElement>;

  ngAfterViewInit(): void {
    ace.config.set("fontSize", "14px");

    // defining custom highlighting rules
    const customHighlightRules = function () {
      this.$rules = {
        start: [
          {
            regex: /\b(sometext|othertext)\b/,
            token: 'keyword',
          },
        ],
      };
    };
    const oop = ace.require('ace/lib/oop');
    const TextHighlightRules = ace.require('ace/mode/text_highlight_rules').TextHighlightRules;
    oop.inherits(customHighlightRules, TextHighlightRules);

    const Mode = function () {
      this.HighlightRules = customHighlightRules;
    };
    oop.inherits(Mode, ace.require('ace/mode/text').Mode);

    ace.define('ace/mode/custom', [], function (require, exports, module) {
      exports.Mode = Mode;
    });

    const editor = ace.edit(this.editor.nativeElement);
    editor.getSession().setMode('ace/mode/custom');
  }
}

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

Vue 3 with Typescript - encountering a property that does not exist on the specified type error

I'm currently working on populating a component with leads fetched from an API. In my setup, I have a LeadService file and a Vue template file. The challenge I'm encountering is related to using an async call in my template file. Although the cal ...

What is the method for selecting a specific row in a Primefaces Datatable using HtmlUnitDriver and Selenium?

Check out this code snippet: import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import org.openqa.selenium.htmlunit.HtmlUnitDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriv ...

position the tooltip within the ample available space of a container in an angular environment

In my editor, users can create a banner and freely drag elements within it. Each element has a tooltip that should appear on hover, positioned on the side of the element with the most space (top, left, bottom, right). The tooltip should never extend outsid ...

The session data is not persisting in the express-session package

I am currently learning about HTTPS and working on implementing a login/logout function. In this function, I store the userId in the session when I login using the POST method. However, when I try to retrieve user information for the next components usin ...

Reduce XSLTProcessor output by 50%

I have a persistent problem (from my perspective, at least). Every time I use XSLTProcessor.transformToFragment, the output is consistently halved compared to the input. For example, when I receive 200 entries in an XML file as a response from a webservi ...

Float and tap

Can someone assist me with my code? I have 4 identical divs like this one, and when I hover over a link, all the elements receive the same code. <div class="Person-team"> <div class="profile-pic-d"> <a cl ...

When I attempted to run `npm start`, an error with status code 1 was thrown,

Upon running npm start, the following error is displayed: > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2d4c5d5d6d1d031c031d">[email protected]</a> start /Users/user/Desktop/react-tutorial > react-script ...

Exploring the process of retrieving array elements from an AJAX response transmitted from PHP

Here is an example of jQuery code for an ajax function: $(document).ready(function() { $("#zip_code").keyup(function() { var el = $(this); var module_url = $('#module_url').val(); if (el.val().length === 5) { $.ajax({ ...

Are the missing attributes the type of properties that are absent?

I have a pair of interfaces: meal-component.ts: export interface MealComponent { componentId: string; componentQuantity: number; } meal.ts: import { MealComponent } from 'src/app/interfaces/meal-component'; export interface Meal { ...

Combining different sub types using the | symbol - Exploring the power of Union Types

I have a custom type called Entry which includes: export type Entry = { number: number position: number entryItem: Banana | Orange } Additionally, I have defined the following types for entryItem: Banana Type export type Banana = { number: number ...

Using the CdkDragDrop functionality alongside the ngTemplateOutlet

I'm experimenting with the Drag&Drop functionality introduced in Angular Material 7. To make my template more modular, I've utilized ngTemplateOutlet to create reusable components. Each option can either be a primary Thing™ or a nested Thi ...

Is there a way to receive messages from background.js of a Chrome Extension within an Angular web application?

I've developed a Chrome Extension that sends messages to all tabs (through background.js) using the following code: chrome.tabs.query({}).then((tabs)=> { if (tabs) { tabs.forEach(tab => { chrome.tabs.sendM ...

Find out if a dynamically imported component has finished loading in Nextjs

Here is a simplified version of my current situation import React, { useState } from 'react'; import dynamic from 'next/dynamic'; const DynamicImportedComponent = dynamic(() => import('Foo/baz'), { ssr: false, loading ...

Fixing the forwardRef issue with react-router-dom and material-ui

Despite implementing the forwardRef as recommended in various posts and Material-UI website examples, I am still encountering a warning in the console that has me puzzled. I am working on setting up a drawer with a list of items that are React Router link ...

What is the process for obtaining an AccessToken from LinkedIn's API for Access Token retrieval?

We have successfully implemented the LinkedIn login API to generate authorization code and obtain access tokens through the browser. Click here for image description However, we are looking to transition this functionality to an ajax or HTTP call. While w ...

What is the best way to bring in an external webpage using Jquery and Custom variables into an Iframe?

Is it possible to use JQuery to load a page into an iframe? I have a specific page that generates a custom printable PDF and I want it to be loaded into an iframe for user convenience. Since I utilize jQuery to fetch all the necessary variables, I cannot ...

Django enables anonymous Ajax requests to reach a Generic View

Here is the current progress I have made: from django.views.generic import View from django.views.decorators.csrf import csrf_exempt class ConfigurationView(View): @csrf_exempt def dispatch(self, *args, **kwargs): return super(Configurati ...

Utilize the Tab feature effectively in Impress.Js

Currently, I have disabled the Tab key in Impress.js so that it only moves to the next slide. However, when I try to focus on links and delete this code to let it behave normally, Impress.js crashes. Has anyone found a workaround for this issue? Appreciat ...

Having trouble accessing the div element inserted by the Angular application

I've encountered an issue while trying to access a div that is injected into the DOM by an Angular app on the page. Below is the script I have placed at the end of the HTML page: $(document).ready(function () { var targetNode = document.querySelect ...

Adjust the viewport width based on the width of the device

Having difficulty adjusting the meta tag viewport content width based on device width, I am struggling to achieve my desired outcome. Here is the code snippet I have been working with: Code snippet: <meta id="viewport" name="viewport" content="width=d ...