Join the Stack Overflow Community
Stack Overflow is a community of 6.5 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

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);
    }
}
share|improve this question
1  
Are you using modules? That is, are you using import/export? If so then your class is not defined on the 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
1  
For your window[suchAndSuch] comment: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… – Mike Cheel Sep 14 at 12:12
    
Aha, illumination. Thanks Mike. – serlingpa Sep 14 at 12:19
1  
Check my answer to this question: stackoverflow.com/questions/39105390/… Does that help? – Nitzan Tomer Sep 14 at 13:26
1  
Seems to work: playground – Nitzan Tomer Sep 14 at 14:25

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.