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

Having trouble fetching information from a JSON file stored in a local directory while using Angular 7

I am currently experiencing an issue with my code. It works fine when fetching data from a URL, but when I try to read from a local JSON file located in the assets folder, it returns an error. searchData() { const url: any = 'https://jsonplaceholde ...

tips for choosing an entire group in ng-select with Angular

I am implementing a multi-select dropdown with groups in Angular using the ng-select component. My goal is to allow users to select an entire group and have all items within that group automatically selected as well. I have been attempting to model my cod ...

jQuery "slide" animation without using <br>

I've been working on a website that incorporates the jQuery "Slide" effect. I have implemented this effect multiple times, using it on 3 different div tags. Each line consists of one "Dynamic" div tag (the moving one) and one "Static" div tag (the tri ...

Improving Vue Component on Navigation

I am facing an issue with my navbar where I have two versions. Version 1 features a white text color, while Version 2 has black text. The need for two versions arises due to some pages having a white background, hence the requirement for black text. Bot ...

Selected value is not displayed in the textbox when using autocomplete feature

---Ajax---- An issue has arisen with the autocomplete feature. While typing "wi" (for example, wipro), the drop-down list appears as expected. However, if only "wi" is selected in the text box, $(document).ready(function () { $("#company_name").key ...

The layout of my website appears distorted on mobile devices

When I view my website, http://www.healthot.com, on an iPhone or other mobile device, the page doesn't display correctly. It scales the window, requiring me to zoom out to see the entire page. To better understand the issue, please refer to this photo ...

Tips on creating a horizontal scrolling effect using the mouse

Is there a way to enable horizontal scrolling by holding down the mouse click, instead of relying on the horizontal scroll bar? And if possible, can the scroll bar be hidden? In essence, I am looking to replicate the functionality of the horizontal scroll ...

Retrieving Browser URL using Node.js

Currently, I am trying to extract the browser URL from a user who has integrated my external JavaScript file into their website. The process involves them including the JS file, which triggers an Ajax call using jQuery to communicate with my Node server. ...

Detecting Unflushed Requests in Jasmine and AngularJS

I'm encountering some issues passing certain tests after implementing $httpBackend.verifyNoOustandingRequest(). Interestingly, excluding this from my afterEach function allows the tests to pass successfully. However, including it causes all tests to ...

The custom declaration file for the 'react-dates' module could not be located

I've been struggling to create a custom declaration file for the 'react-dates' npm package, but I'm facing issues with the compiler not recognizing my declaration file. Whenever I try to import DateRangePicker from 'react-dates&ap ...

Tips for composing a single aggregation within a query

In my query, I wanted to find the first record with a CREATE_DATE greater than or equal to a specific date and less than another date. After calculating the duration between these dates, I needed to write another query. However, I was unsure how to combine ...

Merge requirejs modules using build script

I am attempting to merge and compress require modules into a single file. For instance, if I have a file named article.js with the following content: define(["jquery","flexslider","share_div"],function(){}); I wish for all these dependencies to be merge ...

A guide on extracting content from a PDF file with JavaScript

Hey there, I'm experimenting with various methods to extract content from a PDF file but so far nothing seems to be working for me. Even when I try using pdf.js, it shows an error and I can't figure out why. This is the approach I've been tr ...

Unable to engage with MUI stepper and modify a value

I am hoping to utilize an MUI stepper in place of a Select component. The current Select component is being utilized to signify the status of the document that the user is currently working on (New, In Progress, Complete, etc.). While I have successfully d ...

Maintaining accurate type-hinting with Typescript's external modules

Before I ask my question, I want to mention that I am utilizing Intellij IDEA. In reference to this inquiry: How do you prevent naming conflicts when external typescript modules do not have a module name? Imagine I have two Rectangle classes in different ...

Modify the Div background color by accessing the HEX value saved in a JSON file

(I made a change to my code and removed the br tag from info2) Currently, I have successfully implemented a feature using jQuery that reads color names and hex values from a JSON file, populates them in a drop-down select menu (which is working fine). Now ...

Exploring ways to access data stored in interconnected models, such as MongoDB and NodeJS

As a newcomer to querying, I attempted a unique exercise to practice but unfortunately did not achieve the desired outcome. I have three models: const userSchema = new Schema({ info1: String, info2: String }, const serviceSchema = new Schema( { name ...

Linking to a Different Tab without Tab Mutation with Bootstrap 3.3.5

I am facing a similar issue to the mentioned questions. I am trying to use a link to change tabs, but the problem is that the link only changes the tab content and not the active tab. The most similar question can be found at: Bootstrap linking to a tab w ...

Select the input based on the name and value provided from a radio button using jQuery

I want to show a div element when the user chooses option 4 from a radio button. $(document).ready(function () { $("#GenderInAnotherWay").hide(); $("input[name='Gender'][value=4]").prop("checked", true); $("#GenderInAnotherWay").tog ...

Can a link be generated that swaps out the original URL redirect for the following visitor upon clicking?

Can the program be fed with a list of links to automatically redirect to the next URL once clicked? In this setup, each visitor would only see one link and not have access to any other URLs in the chain. Is there a way to make this happen? Any suggestion ...