Generating an instance of a class by using the class name as a string

Before jumping to conclusions, please take a moment to read the following:

In addition to TypeScript, my issue also involves Angular2.

Main Goal

I am in need of a method in app.component.ts that can take a string (Class Name) and generate an instance of that class. These classes are located in other ts files.

Scenario: I have a method

getWidgetObjectFromClassName(className : string) : Object{}
that is expected to return instances of the class name provided in string format. However, there is a problem.

I attempted to use Namespace and tried

let instance = new SampleNS['OtherName']();
(SampleNS being a namespace), which worked flawlessly in a single file scenario.

The Issue: Now that I have multiple ts files such as interfaces.ts, classes.ts, otherclasses.ts. I am utilizing export namespace SampleNS{} in interface.ts, all functioning correctly. Next, in classes.ts, I am using

/// <reference path="interfaces.ts" />
and the same namespace SampleNS.

Now, my method

getWidgetObjectFromClassName(className : string) : Object{}
resides in xyz.ts, and I am stuck on which import I should provide. The problem lies in the fact that I can only import the namespace from a single file, even though it is the same, thus limiting my ability to create instances to that specific file's namespace.

Plunker Link https://plnkr.co/edit/pt90F34KPsGoHDpSUQFD?p=preview

Answer №1

When importing, remember to utilize as like so:

import * as widgets from './lib';
...
this.widgetInstance = new widgets[className](); 

Check out this Plunker example

I recall seeing this technique in a previous response, although I can't locate it now to offer proper attribution :-/

Answer №2

To instantiate an object from a class name, you can utilize the eval function:

class AnotherClass
{
    a: number;
    b: number;
    constructor() {
        this.a = this.b = 2;
    }
}

function getObjectFromClass(nameOfClass : string) : {}
{
    return eval("new " + nameOfClass + "();");
}

console.log("%o", getObjectFromClass("AnotherClass"));

Check out the sandbox

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

The functionality is verified in Postman, however, it is not functioning properly when accessed from my client's end

I am working on a project where I have a button in my client's application that is supposed to delete a document from a MongoDB collection based on its ID. Here is the backend code for this functionality: index.js: router.post('/deletetask' ...

Guide: Implementing material-ui theme with redux in gatsby

I'm currently utilizing the material-ui theme in conjunction with redux-toolkit within a gatsby project. This is my theme.ts file: import { createMuiTheme } from "@material-ui/core"; import { useSelector } from "react-redux"; import { State } from ". ...

Containerizing Next.js with TypeScript

Attempting to create a Docker Image of my Nextjs frontend (React) application for production, but encountering issues with TypeScript integration. Here is the Dockerfile: FROM node:14-alpine3.14 as deps RUN apk add --no-cache tini ENTRYPOINT ["/sbin ...

Is there a way to retrieve keys of the object from this combination type?

Can someone please help me understand how to retrieve keys from this union type? The Value is currently being assigned as a never type. I would like the Value to be either sno, key, or id type Key = { sno: number } | { key: number } | { id: number }; typ ...

Unable to link the second array to the angular-dual-listbox

I am struggling to connect my JSON data with the Confirmed list in an angular-dual-listbox component created by czeckd. The source part appears correctly, but the Destination list is not displaying the expected results. I have set up a live example on Sta ...

Error in TypeScript: The property "component" is not found on the React MUI MenuItem

I am currently working with the react mui MenuItem component and I am trying to turn a menu item into a link. Here is how I have attempted to achieve this: <MenuItem component={<Link href={`/backend/api/exam/${row.id}/result`} />} className={c ...

How can I personalize a Leaflet popup with image thumbnails and additional customization options?

I've been researching and trying out different solutions, but so far none of them have worked for me. My goal is to dynamically add a title, image, address, and name to popups on my leaflet map as data comes in. However, I'm experiencing some cha ...

Trouble with Angular not Displaying BootStrap 5.0 Styles

Trying to implement both BootStrap and Angular into the project, I successfully applied the styles by adding the following line in the index file: <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="sty ...

Utilizing Typescript generics with an optional second parameter

Learning about generics in typescript has been quite challenging for me. However, I was able to make it work successfully. export type Events = { LOGIN: undefined NAVIGATION: { screen: string } SUPPORT: { communication_method: 'chat&ap ...

Encountering the following error message: "E11000 duplicate key error collection"

Currently, I am in the process of developing an ecommerce platform using the MERN stack combined with TypeScript. As part of this project, I am working on a feature that allows users to provide reviews for products. The goal is to limit each user to only o ...

Declaration of React conditional props in TypeScript

I am facing an issue with my React component where the type is determined by a runtime variable (isMock). I am struggling to get the TS declarations to function properly: The component can either be MockedProvider or ApolloProvider from @apollo/client, ea ...

Autoplay feature on Ionic 3 dynamic image slider pauses when manually sliding images

When I retrieve image slider data from a provider's REST API, the autoplay feature works perfectly. However, after manually sliding through the images, the autoplay function stops working. When I try to use ionViewDidEnter(), it triggers an error... ...

Setting up Windows authentication for an ASP.NET Core 6.0 and Angular project: A complete guide

Attempting to set up Windows authentication with the ASP.NET Core 6 Angular template. Here is the current configuration in use: The following configuration has been added to the program.cs file: // Add services to the container. builder.Services.AddContr ...

retrieving class instances from a Firebase database

I have a new group called GroupA group A { value1: string; value2: string; total(): number { return value1 + value2; } } I want to store instances of GroupA in my database, but when I retrieve them, they are in Object format which does not a ...

What is the process for retrieving an element from component interaction?

Is there a way to dynamically change the background color based on component interaction? I am looking for a method to compare the target element with the current element. For example, here is a hypothetical scenario: <span [style.background]=" ...

Encountering a GitHub REST API CORS issue while attempting to fetch a public repository's git archive

I'm currently working on developing an Angular application that will be hosted on my GitHub pages using a custom verified domain. Below is the code I am using to call the GitHub API in order to obtain the zip archive of one of my (public) repositori ...

The Angular2 framework will sometimes send an OPTIONS method request instead of an http.GET when

I am currently attempting to implement basic authentication in my Angular2 application. public login() { // Setting basic auth headers this.defaultHeaders.set('Authorization', 'Basic ' + btoa(this.username + ':' + thi ...

Adaptable Bootstrap Button that Adjusts to Different Screen Sizes

I want this button to adjust its size according to the screen dimensions. The current code keeps the button fixed in place. See below for the code snippet. <button type="button" [className]="'btn btn-block m-0'" kendoButton ...

Difficulty retrieving information using AngularJS service post selection of item

Currently, I am working on a project involving an AngularJS application. While using the service testPanelService, I encountered a problem where selecting an item from a list correctly logs the details of the selected item. However, when attempting to fetc ...

Tips for setting up communication between UI and backend applications using Nginx reverse proxy in a Docker environment

We have an Angular UI application and a Java Spring Boot backend application. Our goal is to deploy them in Docker containers and establish seamless communication between the front-end and back-end without hard-coding URLs or other specifics. Everything ne ...