Creating classes dynamically in Angular2 and Ionic2

Dealing with a dilemma here. I am attempting to dynamically create an instance of a class from its superclass. Essentially, I have an AbstractClass and multiple classes that inherit from it.

Check out this functional example in the TypeScript playground :

class AbstractGreeter {
    static get(the_msg) {
        let class_name = (<any>this).name;
        // ... do other things here !
        var instance = Object.create(window[class_name].prototype);
        instance.constructor.apply(instance, [the_msg]);
        return instance;
    }
}
class Greeter extends AbstractGreeter {
    greeting: string;
    constructor(message: string) {
        super();
        this.greeting = message;
    }
    greet() {
        return "Hello, " + this.greeting;
    }
}

let second_greeter = Greeter.get("it's me");

let button = document.createElement('button');
button.textContent = "Say Hello";
button.onclick = function() {
    alert(second_greeter.greet());
}

document.body.appendChild(button);

While this code functions smoothly in the playground, I am facing issues implementing it in my ionic2/angular2 application.

The problem arises when window[class_name] is undefined. Even when I tried using a hard-coded string, it didn't work as expected.

Any suggestions on how to rectify this issue?

Appreciate your help!

Julian

Answer №1

Here is a suggested approach for you to try:

  • First, create a parent class as a provider
  • Next, inject this class into the child classes
  • Finally, instantiate the parent class in the constructor of the child class

Don't forget to import and inject these classes into app.module.ts so that they can be accessed throughout your application.

Check out this link for more information on Ionic 2 imports

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

Discovering all words enclosed by '#' in a string using React TypeScript

Trying to figure out how to extract words between '#' in a given string... For example: const str = `<Table striped bordered hover> <thead> <tr> <th>#project name#</th> <th>#First Name#& ...

Encountering an issue while trying to upgrade angular from version 8 to version 16. The error message states: "Unable to bind to 'something' as it is not recognized as a property of 'something'."

Currently in the process of upgrading an old Angular 8 project to Angular 16. The update has been completed, however, when compiling the project I am encountering multiple errors related to components not being able to bind to certain properties that are s ...

What is the best way to retrieve the Object key for the connected object in angularFire2?

When I search the database using a user key, I check if an associated object exists: let url = ``/userMember/${userKey}``; const userMemberRef = this.af.database.object(url, { preserveSnapshot: true }); userMemberRef.subscribe(data => { if(data.val ...

How can I display two slides at once in Ionic 2/3 on a wide screen?

I have been searching for a solution that will allow me to display 1 ion-slide if the device screen is small, but if it's larger, then I want to display 2 ion-slides. Unfortunately, I have not been able to find a suitable solution yet. As an example, ...

Looking for assistance in correctly identifying types in react-leaflet for TypeScript?

Embarking on my 'first' project involving react-scripts-ts and react-leaflet. I am attempting to create a class that should be fairly straightforward: import {map, TileLayer, Popup, Marker } from 'react-leaflet'; class LeafletMap exte ...

Debugging local Messenger: BotFrameworkAdapter cannot find activity type

I have been developing my bot locally using the bot emulator and everything has been working smoothly. Now I am in the process of integrating it with Messenger and trying to run it locally as well. I am attempting to establish a connection from Messenger ...

Unraveling the HTTP response in Angular - Troubles with JSON parsing

After spending a considerable amount of time, I have reached the stage where I am able to receive the following body in a 404 error response from my server. However, I am encountering difficulty in parsing the content into Angular in order to use it. I rea ...

Retrieve a formatted item from a JSON document

Within my Next.js project, I have implemented a method for loading translations and passing them into the component. Here is an example: import "server-only"; import i18nConfig from "../../i18n-config"; const dictionaries = { en: () ...

Having trouble accessing the 'add' property of Rxjs Subscription

I have been working on optimizing my code and I encountered an issue with unsubscribing from multiple subscriptions in ngOnDestroy. Specifically, when trying to invoke the add() method to include additional child subscriptions, I keep getting an error me ...

Steps to modify the background color of an IconButton upon clicking in Material UI

After clicking on the IconButton, the background color changes to an oval shape. I now need to modify the background color when it is clicked. CSS The CSS code for the IconButton changes the background color upon hover. I require a similar effect for the ...

How can I subtract a value from my array in Angular?

I've been troubleshooting this problem for a while now and I'm hoping that someone here can assist me with finding a solution. The issue at hand involves an array object containing various values such as id, title, amountCounter. Specifically, t ...

Establish a global variable within a TypeScript file

I am currently facing an issue where I need to add an event to the browser inside the CheckSocialMedia function. However, it keeps saying that it could not find the name. So, my question is how do I make the 'browser' variable global in the .ts ...

Angular 2 - The creation of cyclic dependencies is not allowed

Utilizing a custom XHRBackend class to globally capture 401 errors, I have encountered a dependency chain issue in my code. The hierarchy is as follows: Http -> customXHRBackend -> AuthService -> Http. How can this problem be resolved? export cla ...

"Troubleshooting Console Errors in NextJS with TypeScript Integration and Fluent UI Components

I am currently working with NextJS, TypeScript, and Fluent UI. To set up the app, I used the command yarn create next-app --typescript. Afterwards, I incorporated Fluent UI into my project by running $ yarn add @fluentui/react. So far, I have not made an ...

Execute a function once an observable variable has been successfully initialized

I'm currently putting together a chat application using socket.io in Angular. I've encountered an issue where I can't seem to execute a particular code or function right after an observable variable is initialized through subscription. The i ...

I'm encountering an unexpected error as I attempt to incorporate a bootstrap template into my Angular application. What could be causing this issue

I am not very experienced with front-end development, so for my current project, I have decided to utilize a pre-made Bootstrap template. I am in the process of integrating it into my project, relying more on my intuition rather than technical expertise du ...

Display various items from a predefined list using Angular's *ngFor directive

Within my Angular project, I am managing a list of reports. This list is structured as an array with a base class to accommodate different types of reports. Even though the list is defined as type: ReturnReport, the individual items can vary between type: ...

When the required attribute in Angular2 is conditional and the value is empty, the field will be adorned with the ng-valid class

In my current project using Angular 2.3.1, I have incorporated the following HTML element into a component template: <input class="form-control" type="text" id="password" name="password" placeholder="Password" [attr.required]="requirePasswd ? true : n ...

Utilize the npm module directly in your codebase

I am seeking guidance on how to import the source code from vue-form-generator in order to make some modifications. As a newcomer to Node and Javascript, I am feeling quite lost. Can someone assist me with the necessary steps? Since my Vue project utilize ...

Create a d.ts file in JavaScript that includes a default function and a named export

While working on writing a d.ts file for worker-farm (https://github.com/rvagg/node-worker-farm), I encountered an issue. The way worker-farm handles module.exports is as follows: module.exports = farm module.exports.end = end When trying to replica ...