Customizing the text color of words that originated from a dropdown selection within an Angular textarea editor

My Process:

Within my interface, I utilize both a dropdown menu and a textarea field. I input text into the textarea and select certain words from the dropdown menu to add to the textarea. I have successfully completed this task.

The Issue at Hand:

Now, I am looking to distinguish the words that originate from the dropdown menu. Specifically, I aim to display these particular words in a red color. Any word entered through the dropdown menu or manually entered word that matches one of the dropdown menu values should be displayed in red. This is the functionality I am striving to achieve. Despite my efforts to find a solution on stackoverflow, I have been unsuccessful thus far. I would greatly appreciate any assistance this community can provide.

My Code:

HTML Markup:

<textarea #text [(ngModel)]='textValue' rows="10" cols="70">
</textarea>
<div>
  <mat-form-field class="input-style">
    <label>Dropdown Menu</label>

    <mat-select (change)="changeValue($event)">
      <mat-option *ngFor="let li of list4" [value]="li">
        {{li}}
      </mat-option>
    </mat-select>
  </mat-form-field>
</div>

My TypeScript:

  changeValue(ev) {
        this.textValue += ` ${ev.value}`;
      }

Feel free to check out my stackblitz for a live demonstration: https://stackblitz.com/edit/angular-mat-form-field-tfw6de?file=app%2Fform-field-prefix-suffix-example.ts

Answer №1

Update 04-04-2021 make sure to check out Owen Kevin's response on this SO thread as my code does not account for "scroll"

To "highlight" text within a textarea, you need to have two layers: one with a textarea and another with a div using [innerHtml]

The challenge with using a textarea is that you must use the same font-family as the div

Based on this codePen example, the HTML structure is as follows:

<div class="container" [style.width]="text.getBoundingClientRect().width+'px'"
                      [style.height]="text.getBoundingClientRect().height+'px'">
  <div class="backdrop">
    <div class="highlights" [innerHtml]="textFormatted"></div>
  </div>
  <textarea #text [ngModel]='textValue' (ngModelChange)="change($event)" rows="10" cols="40">
</textarea>
</div>

A function called "formatted" is used:

  formatted(message:string)
  {
    return message.replace(/\n/g, "<br />").replace(this.regExpr,"<mark>$&</mark>")
  }

This function replaces the selected words in the message with a "mark"

  regExpr=new RegExp(this.list4.map(x=>'('+x+')').join('|'),"g");

Remember to call this.formatted each time you change the textarea content

  changeValue(ev) {
    this.textValue += ` ${ev.value}`;
    this.textFormatted=this.formatted(this.textValue);
  }
  change(message:string)
  {
    this.textValue = message;
    this.textFormatted=this.formatted(this.textValue);
  }

Furthermore, the .css to style the mark should be in the styles.css file

Update to italicize the text, the textarea color needs to be transparent while the "highlight" is colored. However, this may impact the cursor.

.highlights {
    ...
    color: #444;
}
textarea {
  ....
  color: transparent;
}

You can utilize -webkit-text-fill-color for this purpose, though it's not a standard CSS property (works on FireFox, Chrome, and Edge)

@supports (-webkit-text-stroke: 1px black) {
  textarea {
    color:#444;
    -webkit-text-stroke: 1px transparent;
    -webkit-text-fill-color: transparent;
  }
}

For a modified version, refer to the updated stackblitz

Answer №2

If you want to customize the colors of text within a <textarea>, it's not possible. However, you can utilize the contenteditable attribute to achieve the desired effect using a <div>, <span>, or <p>.

For guidance on altering colors within an editable div, visit: https://example.com/editable-div-colors

To incorporate jQuery styling in your Angular TypeScript code, remember to include the following import statement:

import $ from 'jquery';

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

Mapping various sets of latitudes and longitudes on Google Maps

I am working with multiple latitude and longitude coordinates. var latlngs = [ {lat:25.774252,lng:-80.190262}, {lat:18.466465,lng:-66.118292}, {lat:32.321384,lng:-64.757370}, {lat:25.774252,lng:-80.190262}, ]; The coordinates were ret ...

Detach attention from TextField select component in Material UI and React through manual means

When I create a select input using the TextField component from Material-UI library, I need to manually remove focus after an option is selected. I attempted to achieve this by using a reference to the TextField with the 'inputRef' prop. However, ...

What is the best way to update a deeply nested array of objects?

I have an array of objects with nested data that includes product, task, instrument details, and assets. I am attempting to locate a specific instrument by supplier ID and modify its asset values based on a given number. const data = [ { // Data for ...

What is the reason that when a <div> click on a mobile device includes a jQuery ('#item').fadeOut() function, the CSS of the '#item' element maintains its previous hover state

While creating a mock back to top button, I encountered an issue with my jQuery call to fadeOut() behaving differently on mobile devices (this discrepancy can be observed using any desktop browser simulator). You can find the source code here: https://cod ...

Revealed the previously hidden private variables within the Revealing Module Pattern

I have encountered an issue while implementing the Revealing Module Pattern, as I am struggling to expose a modified private property. var myRevealingModule = (function(){ var name = 'Samantha'; function updateName () { name = ...

showing information from a table column

Utilizing the jQuery DataTables plugin with a JSF <h:dataTable>. The page contains 86 records. +++++++++++++++++++++++++++++++++++++ + SN. + Name + Email + +++++++++++++++++++++++++++++++++++++ + 1 + Name 1 + Email 1 + + ...

Adding android to the ionic platform leads to the subsequent error message

I am currently facing an issue while attempting to integrate the Android platform into my Ionic 2 project. The error message I'm encountering is as follows: Error: Cannot find module 'internal/util/types' at Function.Module._resolveFilename ...

mandating the selection of checkboxes

Currently, I am exploring the possibility of automatically selecting a checkbox when an option is chosen from a dropdown menu. Below is a code snippet that demonstrates what I am aiming to tweak: $('.stackoverflow').on('change', func ...

Application utilizing Meteor to connect with external websites or applications

Hey everyone, I'm in the process of developing an application that features a directory of stores. One key requirement is that each store has a unique view created with either Flash or JavaScript. The special view components have already been develope ...

Conquering Challenges Across Multiple Disciplines

Is there a solution to solving the cross domain issues that arise when trying to fetch data from a different web server on the client-side, in violation of the Same Origin policy? ...

Is it deemed as an anti-pattern to establish directives for styling?

Currently, I am in the midst of developing a specialized component UI library for a specific project I'm involved in. This library will consist of unique stylized components with elements that are reused throughout. As I work on this project, I find ...

How to handle Component binding change events in AngularJS

I have developed a component in AngularJS that displays data. However, when the customer binding changes, I need to call a service in the component controller, but it is not updating. Below is the code snippet: In my Test1.html file: <tab-customer tit ...

Is it possible to utilize the HttpXsrfInterceptor and HttpXsrfCookieExtractor classes for CSRF configuration in Angular 16, despite Intelli-J indicating that they do not exist?

In a valuable article about configuring CSRF for Angular, two options are outlined: First: opt for the default Csrf configuration: providers: [ { provide: HTTP_INTERCEPTORS, useExisting: **HttpXsrfInterceptor**, multi: true } ] Second: If you're usi ...

Cucumber Wrangler

I am completely new to using protractor/cucumber and restler in Typescript. The code below is what I have so far for hitting an endpoint URL and getting the response: Given('Hit the {string}', async (string) => { browser.quit() var data: ...

What is the process of utilizing one object inside another object using Angular's subscribe method?

Currently, I am attempting to establish two distinct objects: a user and a manager. The user object contains an ID, while the manager object possesses a unique ID called idManager, as well as an ID linked to the user object in a OneToOne relationship. The ...

How to transform a JQuery button into a dropdown menu

For inspiration, consider this JQuery UI Button example: http://jqueryui.com/demos/button/#splitbutton Now, how can you create a dropdown menu when the small button is clicked? My main concern is the way .button() alters the button's actual appearanc ...

Using the <video /> tag on a Next.JS page generated on the server side leads to hydration issues

My Next.js app's index page is rendered on the server side by default. During development, I encountered an error that stated: Unhandled Runtime Error Error: Hydration failed because the initial UI does not match what was rendered on the server. Wa ...

Is there a way to create a function in JavaScript that eliminates duplicate Objects within an Array of Objects?

Currently, I'm working on a function to store details of a couch in a JS object with 3 properties locally. The properties include: An ID (obtained from the product URL using a function) A color (retrieved through an event listener) A quantity ...

Manipulating and transforming data through Puppeteer's iterative process into an object structure

As a beginner with the puppetteer library, I'm trying to iterate through Amazon reviews and save each comment as an object. Although my code seems to be functioning, it only retrieves the first comment and then stops. async function scrapeProduct(ur ...

Determining in Angular 8 whether a value has been altered by a user or by a method call

Within my select element, the value is currently being assigned through an ngOnInit call. Here is an example of the HTML code: <select name="duration" [(ngModel)]="exercisePlan.duration" (ngModelChange)="onChange($event)"> <option *ngFor="l ...