Retrieving the Value of a Member in an Object using Angular

Is there a way to retrieve the value of an object in Angular using a variable as the member identifier?

For example:

--> my Angular class object:

Object1 {
name: foo
property2: bar
}

--> my function:

myFunction(memberName: string) 
{ 
   return Object1.membername 
}

--> when executing: myFunction("name") returns "foo"

Is this achievable?

Additional info:

This is the object class:

 import { headerStateColor } from "../header/headerDeviceStateColor.model";
 import { betterNameForDeviceState } from "./deviceStateHelper";

export class deviceModel {
    // Class properties here...
};

This is the class where I need to utilize the "dynamic member"

export class DeviceDetailsComponent implements OnInit {
  // Class methods and variables defined here...
}

An error occurs when attempting to use a variable as an identifier:

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'deviceModel'.
 No index signature with a parameter of type 'string' was found on type 'deviceModel'.ts(7053)

Answer №1

Consider using the bracket notation:

myFunction(memberName: string) 
{ 
   return Object1[memberName]
}


inputProcessing(field: string) {
     if(this.deviceDetailModel != NULL)
     {
       (this.deviceDetailModel as any)[field]
     }
   }

In TypeScript, when accessing object properties using bracket syntax, the object must support indexable type. In your case:

this.deviceDetailModel[field]

deviceDetailModel has indexed keys of the same type as 'deviceModel':

        'deviceState'
        'device_id'
        'mac_address'
         ... and so on

However, since field is of type string and not an indexed key, you encounter an error. To resolve this, either specify deviceDetailModel as any or assign an indexable type to it.

To illustrate with an example, consider a person class:

 class Person {
    name: string;
    constructor(name: string) {
        this.name = name;
    }
}

If we have an object of type Person:

const person1: Person = { name : 'Ritesh' };

Accessing name of person1 with dot notation works fine:

console.log(person1.name) // This will work

But using bracket notation can cause errors if the type is explicitly set, similar to:

const n: string = 'name';
console.log(person1[n])

To fix this issue, either use any:

const n: string = 'name';
console.log((person1 as any)[n]) 

Or make Person an indexable type:

 interface Person {
   {[key: string] : string
 }

By defining keys and values for Person type, the error can be resolved. Check out this playground for more insights: TypeScript Playground

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 Authentication Functionality

I need to create a loggedIn method in the AuthService. This method should return a boolean indicating the user's status. It will be used for the CanActivate method. Here is a snippet of code from the AuthService: login(email: string, password: string) ...

Dealing with custom path problems in Angular 2+ webpack configurations

I am interested in using the @ngneat/tailwind schematics to convert an Angular project into one with a custom webpack configuration. However, after adding this, my scss import paths for fonts and other partial scss files are not resolving, resulting in th ...

Enhanced string key indexer type safety in TypeScript

Discover and explore this online TypeScript playground where code magic happens: export enum KeyCode { Alt = 'meta', Command = 'command', // etc. } export type KeyStroke = KeyCode | string; export interface Combination { comb ...

What are some creative ways to design the mat paginator in Angular?

Looking for tips on how to style Angular Material Paginator to match a Figma design? ...

The elements mat-toolbar, mat-sidenav, and mat-sidenav-container are unrecognized

I've encountered an issue while trying to implement mat-toolbar in my project: mat-menu.component.html: <mat-toolbar color="primary"> <span>Responsive Navigation</span> <span class="example-spacer"></span> < ...

How can I access the component name and parameters during the NavigationEnd event?

We are currently setting up Google Analytics and we want to track the URL, parameters, and components in GA. this.router.events .pipe( filter(event => event instanceof NavigationEnd) ) .subscribe((event: NavigationEnd) => ...

What is the best way to retrieve children generated by a custom HTML component using idiomatic React methods?

I'm currently working on developing a search bar with predictive text input using a custom HTML component. The component generates multiple plain HTML children that I need to manipulate in order to achieve the desired functionality. Specifically, I ha ...

Incorporating the unshift method in JavaScript: A Step-by-

I'm looking to create a new function with the following requirements: Function add(arr,...newVal){ } array = [1,2,3]; add(array,0) console.log(array); //I want this to output [0,1,2,3] I tried creating the function similar to push like this: ...

What is the best way to utilize one service within another service without the need for providers array or providedIn?

How can I use Service1 inside Service2 without having to declare it as a Singleton by defining it in the providers array of a module or using providedIn in the service definition? Instead, I would like to use it at the component level, similar to how we u ...

Angular wrapper for resizing iframes (Obtain height of target site within iframe)

My attempts to adjust the iframe height in Angular 5 based on the content window height have been unsuccessful. This is due to using a different domain URL in the src tag, resulting in a CORS (Cross-Origin Resource Sharing) error. HTML: <iframe id=" ...

What is the best way to implement a selected option in AngularJS 2?

Trying to understand how to preselect an option when displayed, I attempted it with old JavaScript style code or another language. For example: <select> for (x = 0; x < elements.size; x++) { <option value="element.id" if (element.id == selecte ...

When attempting to utilize expo-av in a React-Native project on iOS, the recorded MP4 file encountered an issue when trying to submit it as form data for Open

I've been working tirelessly through the night, trying to record myself on my iPhone using expo-av to capture speech and then upload it to openai's transcriptions endpoint with the whisper-1 model. The recording is saved as an mp4 file, which I ...

What is the best way to configure two different 'projects' build settings in the project.json file of an Nx workspace, similar to how it is done

Within the angular.json file, there are two project configurations available: One is specifically for single-spa, while the other is for local development builds. For more details and access to related images and Git links, please refer to: https://i.sst ...

The 'AppsList' generic type needs to have one type argument specified.ts(2314)

Consider the following interface that represents an array of objects. export interface App { entry: object; content: { label: string; visible: boolean; }; name: string; length: number; } export type AppsList<Response ...

Angular displays X items in each row and column

I've been struggling with this task for the past 2 hours. My goal is to display a set of buttons on the screen, but I'm facing some challenges. The current layout of the buttons doesn't look quite right as they appear cluttered and unevenly ...

Unlimited Scrolling in Angular 2: A Complete Guide

For my current project, I am utilizing angular2-infinite-scroll. My concept is to load 6 items on the initial page load and then add an additional 6 items each time the user scrolls to the bottom of the page. However, I have encountered an issue where the ...

Emphasize the search query in Angular 2

I'm a newcomer to Angular 2 and I'm attempting to accomplish a task similar to the one mentioned in the following post: Highlight the search text - angular 2. I have created a pipe filter and my question is, where should I place the pipe filter a ...

Is it possible to extend an Angular component and then use the base component in an ngFor loop?

Can Angular components be extended? And if so, is it possible to create a list of diverse components (using an ngFor loop) that all extend a common base component? For instance, could a custom menu bar display various types of menu items, such as dropdown ...

Creating a distinct input for each row in a table using Angular 2

I am encountering an issue with inputs being created for each row in my PrimeNG/datatable. The problem arises from the local variable #itsmIncident, which causes confusion when trying to pass values to the "Save" button as there are multiple rows involve ...

Guide on integrating a Single Page Application into an ASP.NET Core library and hosting it from a specific route

Scenario I am working on creating an aspnetcore library or module that will contain a small SPA frontend. The goal is to package the html/js/css files along with the dll, and serve the SPA from a specific path (/some-module) without the need for configura ...