Following a post regarding creating objects dynamically in TypeScript, I have the following code used as a factory to create an object from its name:
public createComponent(context: Object, componentName: string): ComponentRef<ComponentBase> {
this.viewContainer.clear();
var instance =
Object.create(context[componentName].prototype); // <-- fails
let componentFactory =
this.componentFactoryResolver.resolveComponentFactory(instance);
return <ComponentRef<ComponentBase>> this.viewContainer.createComponent(componentFactory);
}
I'm not entirely convinced I understand this window[suchAndSuch]
syntax: what does it mean? Can't find any documentation for it.
In any event it seems that window[myClassName]
is undefined, even though the class in question is defined in the same file. I have looked at the Javascript transpiled from the TypeScript, and the class in question is in scope.
I think.
Help!
-- UPDATE -- I have this code, which is part of an Angular 2 application, that is calling the above method to try to get an instance of a component, injectables and all:
export class CustomUserComponent implements OnChanges {
@Input() componentType: string;
@ViewChild(ComponentDirective) componentAnchor: ComponentDirective;
ref: ComponentRef<GalleriaComponentBase>;
ngAfterViewInit() {
this.ref = this.componentAnchor
.createComponent(window, this.componentType);
}
}
window
object. That post is pretty old (2014), and things can be done better today (probably). Can you include more code and explain your problem and what you want to do? – Nitzan Tomer Sep 14 at 12:07