Before anyone marks this as duplicate please read below,
My scenario doesn't just involve TypeScript but also Angular2.
Objective
I need a method in app.component.ts which takes a string(Class Name) and creates a instance of that. The classes exist in other ts files.
Now to the use case:
I have a method getWidgetObjectFromClassName(className : string) : Object{}
which needs to return the instances of the class name which is in string format.
Now the problem,
I tried using NameSpace and doing let instance = new SampleNS['OtherName']();
(SampleNS is a namespace), works perfectly fine in the case of single file.
But Now
i have multiple ts files lets say interfaces.ts, classes.ts, otherclasses.ts. Im using export namespace SampleNS{}
in interface.ts all works, next in classes.ts using the /// <reference path="interfaces.ts" />
and same namespace SampleNS
.
Now my method getWidgetObjectFromClassName(className : string) : Object{}
is in xyz.ts, and now which import should i give?, my point being if i say `import {SampleNS} from './interfaces'.
The problem here is i can only import a single file's namespace(even though its the same) hence im creating instance is limited to the import of that specific file namespace.
Plunker Link https://plnkr.co/edit/pt90F34KPsGoHDpSUQFD?p=preview
Instantiating a Class When you create an object, you are creating an instance of a class, therefore "instantiating" a class. The new operator requires a single, postfix argument: a call to a constructor. The name of the constructor provides the name of the class to instantiate.
To create instances of a class, you call the class using class name and pass in whatever arguments its __init__ method accepts.
Use as
with imports like
import * as widgets from './lib';
...
this.widgetInstance = new widgets[className]();
Plunker example
I remember this from another answer but I couldn't find it to give some credit :-/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With