Converting a string to HTML in Angular 2 with proper formatting

I'm facing a challenge that I have no clue how to tackle.

My goal is to create an object similar to this:

{ 
 text: "hello {param1}", 
 param1: {
              text:"world", 
              class: "bla"
         }
}

The tricky part is that I want to display it based on the text property, like this:

<span> hello <span class="bla"> world </span></span>

Using a component isn't a viable solution for this issue - my only thought so far is utilizing jQuery, but I'd prefer to avoid it. Open to changing the format of the text property if necessary...

Answer №1

Allow me to propose an interesting concept:

import { Component, Directive, Input, HostBinding } from '@angular/core'

@Directive({
  selector: 'my-design'
})
class MyDesign {
  @Input() information: Object;
  @HostBinding('innerHTML') get content {
    return Object.keys(this.information).reduce((previous, current) => {
      if(current === 'text') return previous;
      const regex = new RegExp(`{${current}}`, 'g');
      return previous.replace(regex, (string) =>{
        return `<${this.information[current].tag} class="${this.information[current].class}">
                  ${this.information[current].text}
                </${this.information[current].tag}>`; 
      });
    }, this.information.text);
  }
}

@Component({
  selector: 'my-application',
  providers: [],
  template: `
    <div>
      <my-design [information]="data"></my-design>
    </div>
  `,
  directives: [MyDesign] 
})
export class App {
  data = { 
    text: "hello {param1} {param2} please again hello {param1}", 
    param1: {
      tag: 'span',
      text: 'world', 
      class: 'bla'
    },
    param2: {
      tag: 'div',
      text: 'hello world2', 
      class: 'bla'
    }
  };
}

Witness the demonstration here http://plnkr.co/edit/G5m7zhybhN5Qdp=preview

Answer №2

Here is one potential solution: Within your component's class:

let myCustomization = {
  greeting : "hello",
  messageText : "world",
  textClass : "custom"
}

In your HTML file:

<span> {{myCustomization.greeting}} <span class="{{myCustomization.textClass}}"> {{myCustomization.messageText}} </span></span>

You can then easily adjust the values of myCustomization properties to create text with a specific class for the messageText. Does this meet your requirements?

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

Unable to download essential dependencies using NPM

After cloning a repository for a MEAN stack application, the first step was to run npm install. The installation process resulted in: added 1580 packages from 1887 contributors and audited 15249 packages in 281.586s found 18 vulnerabilities (5 low, 12 mod ...

MUI useStyles/createStyles hook dilemma: Inconsistent styling across components, with styles failing to apply to some elements

I have been trying to style my MUI5 react app using the makeStyles and createStyles hooks. The root className is being styled perfectly, but I am facing an issue with styling the logoIcon. Despite multiple attempts to debug the problem, I have not been suc ...

Issue with Spring Boot project not updating data from database

Recently, I have been delving into a full stack application project using Angular and Spring Boot for the first time. Following a comprehensive tutorial has guided me through this journey. Starting with a project downloaded from , I included various depen ...

How to use OBJLoader/Three.js to load a specific URL in JavaScript

I am encountering an issue with a JavaScript code snippet from the three.js OBJloader. I should mention that my experience level in JS and PHP is limited as I am just starting out with WordPress websites. My problem lies in utilizing the setPath and load ...

Exploring the source of the "Unexpected token ;" issue in an Express-JS application

Working on a project with Parse and Express-JS, I encountered an issue when trying to display an EJS page. The error message Unexpected token ; appeared while running the command line parse develop MyApp in Terminal. Below is the full stack trace of the er ...

Creating reactive behavior with a Promise initiated within a constructor - A guide

I am facing an issue with my Thing class. In the constructor, there is an asynchronous operation using fetch. Once the fetch completes, the result is assigned to a field in the Thing object: class Thing { constructor() { this.image = null ...

Using the && operator in an if statement along with checking the length property

Why does the console show 'Cannot read property 'length' of undefined' error message when I merge two if conditions together? //When combining two if statements using &&: for(n= 0, len=i.length; n<len; n++) { if(typeof ...

Utilizing generics with Swagger in NestJS

export class PaginatedResult<T> { @Expose() @ApiResponseProperty(type: T}) // It's unfortunate that this isn't working because it's a type but being used as a value @Transform(({ obj }) => obj.data.map((data) => new obj.cla ...

Implementing a variable for an array in Angular 4: A step-by-step guide

I need help determining the correct value for skill.team[variable here].name in Angular, where all team names are retrieved from the skill. Below is the code snippet: HTML <select [(ngModel)]="skill.teams[1].name" name="teamName" id="teamName" class= ...

How can I use Laravel to enter data using the post method?

I've been struggling with data transfer in my Angular component for a while now, specifically using a post method. Despite extensive research and reading various documents, I haven't been able to find a solution. Can you assist me with this issue ...

Can Angular 4 experience race conditions?

Here is a snippet of my Angular 4 Service code: @Injectable() export class MyService { private myArray: string[] = []; constructor() { } private calculate(result): void { myArray.length = 0; // Perform calculations and add results to myAr ...

How can I update the style of my array-bars using componentDidMount()?

I created a visualization tool for sorting algorithms that displays vertical bars with varying heights and sorts them. The "Generate new Array" button triggers a function to generate a new array each time it's clicked, which is also used in the compon ...

Tips on preventing duplication of APIs when retrieving data using nextjs

In my code, I have a function that can be called either from server-side rendering or client side: export const getData = async (): Promise<any> => { const response = await fetch(`/data`, { method: 'GET', headers: CONTENT_TYPE_ ...

Is there a way to determine if a table cell contains overflowing text compared to another cell?

Is there a way to detect if the content of the fourth td overflows from the second td? I am looking for a method to determine which td has overflowed text and identify which td's text is overflowing. What approach can be used to determine which td i ...

Tips for defining the anticipated server response solely based on status and cookie

I am using Redux Toolkit Query to occasionally refresh the jwt token: import { createApi, fetchBaseQuery } from "@reduxjs/toolkit/query/react"; export const refreshApi = createApi({ reducerPath: "apiSlice", baseQuery: fetchBaseQuer ...

The type does not contain a property named `sort`

"The error message 'Property sort does not exist on type (and then shoes4men | shoes4women | shoes4kids)' pops up when attempting to use category.sort(). I find it puzzling since I can successfully work with count and add a thousand separato ...

Challenges with loading content and async JavaScript within websites

I decided to replace the content on index.htm with the content from project.htm. By clicking on a#front, it redirects to project.htm and dynamically updates the content. However, I am facing an issue regarding how to run the javascript that accompanies thi ...

Issue with Material-UI Nested Checkbox causing parent DOM to not update upon selection changes

Currently, I am integrating a nested checkbox feature from a working example into my application. The functionality of the checkboxes covers seven different scenarios: - Scenario - No children, no parent selected - Select the parent -> select both pa ...

The default value for an input of type date should be set to the current date

I am working on a project that involves an input field with the type of "date". I have implemented Materialize to provide a user-friendly date picker. My goal is to set the default value of this input field to the current date when it is initialized. Here ...