Using strings as variable names in Angular 2+ and Typescript can be a powerful tool for creating

In traditional JavaScript, we can assign a property to the global window object using a string as the name, like so:

const str = "myVar";
window[str] = "Value";
console.log(myVar);

However, is there a way to achieve the same functionality in Angular 2/4 and Typescript? While we can store variables in components using this.myVar, can we create a variable with a string as its name? For example:

const str = "myVar";
this[str] = "Value";
// the result should be similar to this.myVar = "Value";

https://i.sstatic.net/dXycF.png

https://i.sstatic.net/r1Mqx.png

Answer №1

If you want to allow dynamic properties on your class, you can do so like this:

class Example {
  [key: string]: any;

  constructor() {
    const str = "myProperty";
    this[str] = "Dynamic Value";
    console.log(this.myProperty);
  }
}

Just keep in mind that by enabling dynamic properties, you are sacrificing typechecking:

class Test {

  [key: string]: any;

  constructor() {
    this.tet(); // causing a typo and resulting in a runtime error
  }

  test() {

  }
}

Answer №2

I believe there is a way to gain access by utilizing the following method, and Typescript acknowledges this format

this["myVariable"] 

in place of

this.myVariable

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

How to apply animation in Angular 2 to a single element within an *ngFor loop

Is it possible to apply animation to only one element when using *ngFor in Angular? Currently, the animation applies to all elements in the cycle, but I want to target only one element. How can I achieve this? .............................................. ...

Displaying form errors in Ionic 3 when values do not match the specified regular expression

I have been working on creating validation forms using ionic/angular and I have successfully implemented checks for empty fields to notify the user that they need to be filled. However, I am now looking to also alert the user when their input does not matc ...

The Angular parent component is able to detect changes in the ng-content child component

I am looking for a way to have a function execute in my parent component when an event is emitted from my child component. The child component is inserted into the parent using ng-content. I have simplified the code but I am struggling to get the child com ...

Best practices for working with Angular: How to handle nested subscribe calls effectively?

My dashboard component has an extended ngOninit function where I need to perform some verifications before the component loads. this.startupSubscription = this.accountService.getInfo().pipe( switchMap(account => { this.account = account; retur ...

Combining nested Observables within an outer array without using inner subscribe (RxJS)

Looking at the TypeScript functions below, which are used for async HTTP-Calls: public retrieveAllMembersIdsFromGroup(groupId: string): Observable<string[]> public retrieveMember(memberId: string): Observable<Member> How can these be combined ...

change in the value of a nested formArray within a parent formArray

I am working with a form that includes a formArray called FinYearArray, which in turn contains another formArray called RecipientArray. Both of these arrays have formControls for the amount, and whenever there is a change in these fields, the totals need t ...

Angular Router is unable to recognize the provided URL

When my app is loaded, I need to perform some logic using the URL as a parameter. Currently, I am working on an Ionic 5 project and in my app.component.ts file, I have the following code: export class AppComponent { constructor(router: Router) { cons ...

Angular input field with the ability to add and remove multiple options

Users can enter multiple emails to be added to a list, and they have the option to remove emails from the list. https://i.sstatic.net/vnHpJ.png ...

Advanced Typescript contains a parameter that specifies the type of callback function

Is it possible to create a function that is more typesafe than the current implementation? public addBusinessRule(targetProperty: string, dependentProperties: string[], callback: (dep0: any, dep1: any, ...)): void { // s ...

Struggling to integrate a JavaScript sdk with an Angular2 application due to missing dependencies

I've been struggling to incorporate the Magic: The Gathering SDK library into my Angular2 application. I've tried various methods, but nothing seems to work seamlessly. When I attempt to import the library using TypeScript like this: import { } ...

Using routing with modules instead of components in Angular 10+ involves configuring the routing paths within the module files

I recently tried implementing modules instead of components for routing in Angular 10, but encountered a white screen issue. Any assistance would be greatly appreciated. Here is the code snippet I've been working with: import { NgModule } from &apos ...

How can we transform a Forkjoin into an iterative process?

I am currently working on creating a single Observable from multiple http requests, and it seems like Forkjoin is the solution. However, the number of calls required depends on the data being requested (e.g., data for a year or a week). Here is the existi ...

Angular Dependency Injection: Individual instances of each service are provided for every module usage

Within my application, there is a module called "FileUpload". The upload service included is "UploadService", which receives a service injection with the interface "RequestService." I also have two other modules: FileManager1 and FileManager2. Each file m ...

The presence of an Angular pipe is causing interference with the execution of a template

I've developed an application that can organize an array of objects in either ascending or descending order based on a specific property value using the custom function sortByField(). Additionally, the app allows users to filter data by entering a sea ...

Is there a substitute for $sce in Angular 7?

Previously, in Angular 1, we utilized $sce to display HTML tags like this: > <p><strong>xyzz</strong> yttryrtyt <span > style="color:#e74c3c">abc</span>.</p> in a user-friendly format. I am now curious about th ...

Utilizing the outcome of the initial promise in subsequent promises within a Promise.all operation

After finding a helpful answer by T.J. Crowder on a SO Thread, I successfully combined a loop of async tasks with Promise.all. The main issue at hand is that I need to first read an excel file in one Promisified function and a list of image files in anothe ...

Encountering a Tslint error while utilizing createBrowserHistory() function imported from @types/history

In my React application, I have imported the @types/history and am utilizing the createBrowserHistory() function that it offers. However, I encountered a tslint error: ERROR in C:/Users/eshan/my-website/src/App.tsx ERROR in C:/Users/eshan/my-website/src/ ...

Error occurs in Azure Function Linux Nodejs when trying to use @azure/storage-blob as it cannot read the property 'startsWith' of undefined

While testing my Azure Nodejs Linux function locally, I encountered this issue with the code snippet below: import { BlobServiceClient } from "@azure/storage-blob"; const connectionString = process.env[ "AZURE_STORAGE_CONNECTION_STRING&qu ...

Issue with Nativescript Angular router version 3.0.0-alpha.7 causing navigation errors

This project example highlights a problem: https://github.com/rrcoolp/test-router-app/ Issue with navigation: The test project showcases an issue with NATIVESCRIPT ANGULAR 2 (RC3) and Nativescript router 3.0.0-alpha.7. The problem is straightforward - na ...

What is the syntax for implementing React.forwardRef in a dynamic Anchor or Button component?

I am working on a component that can act as either a button or an anchor tag. However, I am facing challenges in implementing conditional typing for the ref. How can I resolve this issue and make the ref acceptable? type ConditionalElements = | ({ ...