choose this.variable angular 12 in a dynamic manner

I am facing an issue with selecting pre-defined variables within a component. Here are the variables in question:

public editable1: number = 0;
public editable2: number = 0;
public editable3: number = 0;
public editable4: number = 0;
public editable5: number = 0;

Next, I have an array of arrays:

public editors: []=[
['editable1', 'editable3', 'editable5'],
['editable1', 'editable2', 'editable3']
]

My goal is to increment these variables based on the lists provided in the array.

this.editors.forEach(element => {
  element.forEach(e => {
    this['e']++; // My intention here is to reference the predefined variables, but it's not working as expected
  });
});

How can I resolve this issue?

Edit: The suggested solution works perfectly fine, but I would like to provide additional information regarding syntax for more complex code. I have changed the variable that needs to be edited, and now it is nested inside service.object.object.key:value structure. Therefore, the code looks like this:

this.editors.forEach(element => {
      element.forEach(e => {
        (this.service.object as any)[e].key++; // This allows me to increment the value of an object within an object, which is located in a service
      });
    });

Answer №1

An alternative approach is to cast your component as type 'any', allowing you to access its properties using square bracket syntax like so:

this.editors.forEach((element) => {
      element.forEach((e) => {
        (this as any)[e]++; 
      });
    });

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

Angular: Tailoring the Context Menu

Currently, I am utilizing a helpful tutorial to implement a custom context menu feature. The main issue I am facing is that when a user interacts with the list items, I want the correct index of each item to be displayed. However, at the moment, clicking o ...

What could be causing the lack of updates in my shared service across all components?

I have implemented an Angular2 app where I am initializing an authentication service called LocalStorage which I want to be accessible across all my components: bootstrap(AppComponent, [ ROUTER_PROVIDERS, LocalStorage ]); The definition of the Lo ...

Populating drop-down data from a JSON response obtained using a GET request in Angular 4

I'm attempting to display JSON keys/fields in a dropdown menu for commands, which are of Object type (see JSON below). For example, "key1" and "key2" should be visible in the dropdown. Initially, I used *ngfor but encountered an error - "ngfor onl ...

JavaScript code gives several outcomes

I'm struggling to understand a function that returns multiple types. How does each type get used? function(): Observable<Type> | Promise<Type> | Type { ... } The pipe (|) seems to indicate that the function can return various values. But ...

Can someone explain the distinction between 'return item' and 'return true' when it comes to JavaScript array methods?

Forgive me for any errors in my query, as I am not very experienced in asking questions. I have encountered the following two scenarios :- const comment = comments.find(function (comment) { if (comment.id === 823423) { return t ...

Exploring the Validation of Request Body Attributes in Loopback 4

I am searching for a solution to prevent undesired attributes from being included in the requestBody, based on the specifications outlined in the corresponding Model. Below is my model: import { Model, model, property } from '@loopback/repository&ap ...

How to retrieve the type of a computed keyof T as a generic type within TypeScript

I am working with two different interfaces: interface PersonRequirements{ user:string, password:string, id:number } export interface Requirement<R> { name: keyof R & string, save: () => any,/* I want this return type to be ...

Steps for integrating the ts component into the index.html file

Is there a way to add the ts component in the index.html file? I've been looking for a solution for quite some time now, but haven't had any luck. Can anyone offer any suggestions or help? ...

Populating a data grid with several objects within a JSON object

I am currently developing a project utilizing React with typescript and materialUi. My task is to retrieve data from a JSON fetch request and display it in a DataGrid. The structure of the JSON data is as follows: { id: "1234567890", number: ...

Receiving an eslint error while trying to integrate Stripe pricing table into a React web application

If you're looking to incorporate a Stripe documentation code snippet for adding a stripe-pricing-table element, here's what they suggest: import * as React from 'react'; // If you're using TypeScript, don't forget to include ...

Edge fails to access Webservice from file:/// host

When attempting to access a webservice that I've created in C# using Typescript and the fetch-api, everything works smoothly in Chrome and Firefox. However, in Edge, the access fails. I've tried both POST and GET methods in Edge, but neither are ...

The onChange() function should only consider the last character typed, rather than evaluating the entire line each time

Explanation: I am utilizing the onChange function to detect when someone types the symbol @. Issue: While typing, the code currently checks the entire line each time a character is added, causing a lag in typing speed. I am looking to update the code so i ...

What is the solution to the TypeScript error stating that there is no index signature with a parameter of type 'string' on the 'Object' type?

While working on an Angular project, I came across an issue when writing a Typescript function for a service. The error message stated: "Element implicitly has an 'any' type because expression of type 'string' can't be used to inde ...

The payload from the Axios POST request is failing to reach its destination endpoint

I have two Express servers up and running - a gateway and an authentication service. I am facing an issue where the payload I set in the body of a request from my gateway to the authentication server never seems to arrive, despite there being no apparent C ...

Unable to load the node modules

In my development journey, I created an ASP.NET MVC project using Angular 2 in Visual Studio 2017 and set up node for package management. Here is a snippet from the package.json file: { "version": "1.0.0", "name": "asp.net", "private": true, ... ...

Issue detected in loading ./styles.css in Angular 6

I'm a beginner with Angular 6 and encountered this error in my project: ERROR in multi ./node_modules/bootstrap/dist/css/bootstrap.min.css ./styles.css Module not found: Error: Can't resolve 'C:\Users\User\e-CommerceWebsite& ...

Combining and mapping arrays in Javascript to form a single object

I am using the following firebase function this.sensorService.getTest() .snapshotChanges() .pipe( map(actions => actions.map(a => ({ [a.payload.key]: a.payload.val() }))) ).subscribe(sensors => { ...

Convert an array of strings to my custom array type in Angular

I have a list of different statuses Here is an example of it: export enum InvoiceStatus { Created = 1, Pending = 2, Approved = 3, Rejected = 4, Paid = 5, Deleted = 6, PreparingPayment = 7 } My goal is to convert it into an ar ...

Strategies for Creating a Test Suite for RepositoryFactory in Vue.js/Nuxt.js

Summary of RepositoryFactory Implementation An implementation of the RepositoryFactory pattern has been carried out for API connection in a Vue.js/Nuxt.js application. For more details, refer to this article: here hogeRepository.ts import { NuxtAxiosInst ...

Is it possible to incorporate an interface with a named function in TypeScript (function declaration)?

Just dipping my toes into Typescript and experimenting with interfaces for my functions: interface StringFunction { (arg1: string): string } I managed to associate this interface with a function by declaring it as a variable: let testFunction: Strin ...