Utilizing dynamic variable invocation

When working with Angular Components, I need to utilize various variables.

export class AppComponent{
 value1;
 value2;
 value3;
 value4;
  
 print(position)
 {
   console.log(this['value'+position]);   
 }
  
} 

How can I implement this functionality?

Answer №1

class UserSettings {
    constructor() {
        this.setting1 = "value1";
        this.setting2 = "value2";
        this.setting3 = "value3";
        this.setting4 = "value4";
    }

    display(position) {
        console.log(this['setting' + position]);
    }
}

userSettings = new UserSettings();

userSettings.display(4);

class UserSettings {
    constructor() {
        this.setting1 = "value1";
        this.setting2 = "value2";
        this.setting3 = "value3";
        this.setting4 = "value4";
    }

    display(position) {
        console.log(this['setting' + position]);
    }
}

userSettings = new UserSettings();

userSettings.display(4);

Answer №3

To achieve your desired outcome, simply switch from using dot notation to square brackets notation.

export class Application {
  number1 = 10;
  number2 = 20;
  number3 = 30;
  number4 = 40;

  constructor() {
    this.display(2); // This will show the value of number2
  }
  
  display(pos: number): void {
    console.log(this[`number${pos}`]);  
  }
}

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 with transferring information from JQuery to PHP

Currently, I'm working on transmitting data from jQuery to PHP. Here's an excerpt of what I've done: var jsonArray = JSON.stringify(dataArray); $.ajax({ type: "POST", url: "addcar_details.php", ...

What is the reason for the allowance of numeric keys in the interface extension of Record<string, ...>

I am currently working on a method to standardize typing for POST bodies and their corresponding responses with API routes in my Next.js application. To achieve this, I have created an interface that enforces the inclusion of a body type and a return type ...

What is the best approach for creating a test that can simulate and manage errors during JSON parsing in a Node.js

My approach to testing involves retrieving JSON data from a file and parsing it in my test.js file. The code snippet below demonstrates how I achieve this: var data; before(function(done) { data = JSON.parse(fs.readFileSync(process.cwd() + '/p ...

The dygraphs library is experiencing an issue due to a discrepancy between the number of labels and the number of

Having trouble with the dygraphs. I've extracted an array from PHP that appears like this: data = [ { "DATA": "2016-01-22", "TOTAL": [ "7", "4", "20", "0" ] }, { "DATA": "2016-01-25", "TOTAL": [ ...

Utilize array.map() or array.reduce() to generate a chart array

Presenting an array: this.dataArray = [ { id: 12, status: 2, number: 10 }, { id: 2, status: 2, number: 300 }, { id: 2, status: 2, number: 12 }, { id: 4, status: 2, number: 65 }, { id: 6, status: 2, number: 129 }, { id: ...

Which npm package is most recommended for integrating the Google Maps platform with NEXTJS?

Struggling with integrating Google Maps Platform into my Next.js project. Despite thorough searching, I haven't found a suitable npm package or clear implementation instructions. Any recommendations or guidance on how to effectively integrate Google M ...

What are some solutions for troubleshooting a laptop freeze when running JavaScript yarn tests?

Running the yarn test command results in all 20 CPU cores being fully occupied by Node.js, causing my laptop to freeze up. This issue is particularly troubling as many NodeJS/Electron apps such as Skype, MS Teams, and Slack are killed by the operating syst ...

Jenkins integration with a MEAN stack application: A step-by-step guide

I'm working on a Mean stack application and looking to integrate Jenkins CI into my workflow. I am uncertain about the steps needed to accomplish this task. Currently, I use bower for installing frontend packages and npm for other functionalities. ...

Variable for Sweet Alert Input Box

I am completely new to PHP and JavaScript, so my question is fairly straightforward... I have a JavaScript code snippet (Sweetalert2 text field) and I'm looking to capture the information entered by users in a separate PHP file using AJAX. I've b ...

Reorganize array elements in a different sequence utilizing JavaScript

I possess an array const arr = [ {label: 'a', width: 200}, {label: 'b', width: 200}, {label: 'c', width: 200}, {label: 'd', width: 200}, {label: 'e', width: 200} ]; provided with another arr ...

Aligning form elements horizontally with Angular 2 Material

Thank you in advance for taking the time to assist me. Your help means a lot! I have developed a form using Angular 2 Material Design and I am facing an issue with aligning two elements. Specifically, how can I align Bill Number and Year as shown in the s ...

Tips on leveraging LocalStorage to update state in ReactJS

In my code, an array fetches API data each time componentDidMount() is called. Within this array, each element contains an object with a default boolean value of true. An onClick function toggles the boolean value of a specific element to false when clicke ...

The canvas is being expanded by utilizing the drawImage method

Ensuring the correct size of a <canvas> element is crucial to prevent stretching, which can be achieved by setting the width and height attributes. Without any CSS applied other than background-color, I am faced with an unusual issue. Using ctx.draw ...

Reset input field values in a Reacstrap form with a MERN stack

Recently, I delved into learning the MERN stack. However, I encountered an issue where after adding a new name and organization based on my fields and reopening the modal, the last entered values remain in the form. How can I reset the form each time I r ...

How can I identify the moment when an AngularJS route controller is no longer in scope?

Currently, I have a controller set up to poll the server at regular intervals using $timeout. The issue arises when the route changes - I need to stop the polling and then restart it once the original route is accessed again. If anyone has any suggestions ...

What advantages does utilizing a directive template function offer in AngularJS?

As stated in the documentation, a template can be defined as a function with two parameters: an element and attributes, which returns a string representation of the template. This string value replaces the current element with the HTML content. During repl ...

Tips on activating two HTML buttons simultaneously

I tried to implement clickable tabs by following a tutorial. I created both horizontal and vertical tabs. However, I want to have both buttons active at the same time. For example, if any of the horizontal buttons is active (number less than 6), then the f ...

What is the process for transmitting an array of objects from Angular to a Web API Core using HttpGet?

In my TypeScript file, I have an array of objects called PropertiesParams: const PropertiesParams = [{ Name: 'FirstName', Filter: 'Like1' }, { Name: 'LastName', Filter: 'Like2' }, { Name: ...

Testing in NodeJS - revealing the application

Currently, I am in the process of testing my NodeJS application using supertest. To make my app accessible within test.js at the end of app.js, I have exposed it. /////////////////// // https options var options = { key: fs.readFileSync("./private/key ...

leveraging express.js middleware alongside jwt and express-jwt for secured authentication in express framework

I am encountering an issue while using the express-jwt to create a custom middleware. The error message persists as follows: app.use(expressJwt({ secret: SECRET, algorithms: ['HS256']}).unless({path: ['/login', '/']})); ...