What is the best way to generate a dynamically interpolated string in JavaScript?

I'm currently developing a reusable UI component and am exploring options to allow the user of this component to provide their own template for a specific section within it.

Utilizing TypeScript, I have been experimenting with string interpolation as a potential solution. Here is my progress so far:

export class Pager {
    pageNumber: number = 1;

    getButtonHtml(buttonContentTemplate?: string, isDisabled?: boolean): string {
        buttonContentTemlpate = buttonContentTemplate || '${this.pageNumber}';
        isDisabled = isDisabled || false;
        return `<button id="button-id" type="button"  ${!isDisabled ? '' : disabledAttribute}>
                    ${buttonContentTemplate}
                </button>`;
    }
}

While I have additional methods in place to update the page number based on user input/interaction, my goal is for getButtonHtml to return

<button id="button-id" type="button">1</button>
when called. Unfortunately, it currently returns
<button id="button-id" type="button">${this.pageNumber}</button>
.

I am curious if there is a method to prompt JavaScript to reevaluate the string and interpolate the remaining placeholders?

After reviewing the MDN article on this matter, I suspect that utilizing the String.raw method may provide a solution. However, despite various attempts, I have yet to achieve success.

Any assistance or guidance on this matter would be highly appreciated.

Answer №1

One issue is that Template literals are immediately interpreted.

To resolve this, consider lazy loading the template by passing in a function that returns a string instead.

export class Pager {
    pageNumber: number = 1;

    getButtonHtml(template?: () => string, isDisabled=false): string {
        template = template || function() { return this.pageNumber.toString() };
        return `<button id="button-id" type="button"  ${!isDisabled ? '' : disabledAttribute}>
                    ${template()}
                </button>`;
    }
}

Furthermore, default parameters can be utilized to avoid using the || operator workaround.

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

Checkbox input with alphabetical ordering

I am currently facing an issue with a form that has checkboxes, but the text is not in alphabetical order. While there are plenty of examples for lists, finding examples for checkboxes has been challenging. http://jsfiddle.net/fG9qm/ <form> < ...

Error: The hyperlink in the response from the Ajax request is not functioning as expected

I've exhausted all the suggestions for fixing this issue, but nothing has worked so far. Currently, my setup involves making an AJAX call to a PHP page called livesearch.php from the index page in order to retrieve live search results. <html> ...

The Angular 2 router is not compatible with using the same component but with different IDs

Currently utilizing the alpha8 router with 3 main routes: export const appRoutes: RouterConfig = [ { path: '', component: LandingComponent }, { path: 'blog', component: BlogComponent }, { path: 'posts/:id', compon ...

How to turn off automatic formatting in CKEditor

Whenever data is entered into a field using CKEditor, the Save button becomes enabled. However, if I programmatically set data into the field using Javascript, the Change event always triggers causing the Save button to remain enabled even if the field is ...

Having difficulty accessing the value of a table td element in HTML using a jQuery selector

When creating a table, I utilize ng-repeat to generate table rows. Whenever the dropdown changes, a function is triggered which applies certain conditions. Based on these conditions, an object is added to an array that is bound to a scope variable. Here i ...

How come the button doesn't get enabled after three seconds even though ng-disabled is being used?

index.html <html ng-app='myApp'> <head> <title>TODO supply a title</title> <script src="js/angular.js" type="text/javascript"></script> <script src="js/using built-in directives. ...

IE8 encountering issues with Jquery ajax() request

My current issue involves submitting data using ajax from forms with a class of ajax. This functionality works flawlessly in Firefox, Safari, and Chrome, but is unsuccessful in Internet Explorer. ajax: function() { $('form.ajax').live(&apo ...

Error encountered while deploying to Heroku: cross-env not detected in Node.js application

As I attempt to deploy my project on Heroku, the following error persists despite all my efforts. Please assist me in resolving this issue: { "name": "storybooks", "version": "1.0.0", "des ...

Issue with button events not being triggered while working with dynamically created classes

I am facing an issue with three plus (+) buttons that are next to three separate tables built using DataTables. The problem arises because all the plus buttons were created in one location with DataTables, resulting in them being assigned the same classes ...

Not successfully integrating an angular component

In my Angular application, I am working on creating a new component and injecting it into the app. Below is the code for the angular component: (function(angular) { 'use strict'; angular.module('some.someModule', ['bm.component.t ...

Managing the `selected` property of an option in React/NextJS

I have been working on a website and encountered an issue with a dynamic select box in React. Despite the functionality of my app being intact, I am struggling to add the selected property to an option once it is chosen. Is there a more effective way to ...

What are the best ways to utilize getElementById in React?

As a beginner in React, I am attempting to create an auto text animation for my project. While I have successfully implemented it in VanillaJS, I am facing challenges with doing the same in React. import React, { Component } from 'react' class A ...

completed() versus finished()

As I was going through the documentation for passport, I came across an interesting observation regarding the use of serialize() and deserialize(). It seems that done() is called without being explicitly returned in one scenario. However, while setting up ...

Inheritance of Type Member in TypeScript

My data structure looks like this: export abstract class Person { ... } export class FPerson extends Person { a: A; b: B; } export class JPerson extends Person { c: C; } export class User { person: Person; } When dealing with the s ...

Tips on transforming JSON output into an array with JavaScript

Looking for a solution to convert a Json response into an array using JavaScript. I currently have the following json response: ["simmakkal madurai","goripalayam madurai"]. I need to transform these results into an array format. Any suggestions on how I ...

What are the steps to set up Redis Store in my production environment?

I am currently in the process of setting up Redis as a session store, but for some reason it's not functioning properly. I have integrated passport.js and express-flash, however when I attempt to run the current Redis setup, it fails to work: var ses ...

WebSocket functionality in Node.js utilizing the ws module from npm

I am currently working on developing a chat application. The first step involves the user sending their username, and if the name does not already exist, they are logged in. The user can then send a message to another user. However, an issue arises where a ...

How to Embed a Javascript (jquery) Variable within a JSON Object

I have searched everywhere for a "simple answer" to this problem, but unfortunately, I cannot find a solution that aligns with my understanding of JSON and jQuery. Perhaps I am too much of a beginner in JSON to accurately formulate the right question (and ...

Switching from ejs format to html

I've been working on a tutorial that uses ejs, but I'm not too familiar with it. I'd like to know how to convert the server.js from using ejs to html. Here's the code snippet: app.set('view-engine', 'ejs') app.use( ...

forever js is interfering with the operation of a different application

I currently have two very similar Node JS projects that I manage by starting and stopping them using Forever JS. Both projects can run simultaneously on different ports but, when I input the following command: forever stop index.js In one project direc ...