typescriptangularextendstypescript1.7

TypeScript : Referencing multiple Objects of different types extended from a single base type


I am using Angular 2 with TypeScript.

I have a BaseType component

@Component({})
export class BaseType {
    protected state: string;
    constructor() { }
    setState(state : string) {
        this.state = state;
    }
}

I am extending the same to ComponentOne and ComponentTwo by extending above BaseType

ComponentOne

@Component({})
export class ComponentOne extends BaseType {

    constructor() { }
}

ComponentTwo

@Component({})
export class ComponentTwo extends BaseType {

    constructor() { }
}

I am loading these two components dynamically in another class using following code (partial code)

let component: any;

if(/*condition to show component one*/) {
    this.component = ComponentOne;
} else {
    this.component = ComponentTwo;
}

//Load Component
this
    .loader
    .loadIntoLocation(this.component, this.el, 'field')
    .then((res) => {});

When I use following later in the same file :

this.component.setState("state");

It is triggering error

TypeError: this.component.setState is not a function(…)

What type should I use on component (currently it is any), or use any casting, so that accessing setState method on this.component should work without any issues?

Thanks in advance!


Solution

  • Got the issue.

    What fixed my code :

    Angular 2 returns a promise for loadIntoLocation along with a reference to the newly created Component instance.

    So, I created another local variable with the type : ComponentRef which can be loaded from angular2/core.

    But this is only a component reference and it doesn't contain actual instance.

    ComponentRef provides another property with the name instance to access it's methods.

    Working Code

    let componentRef: ComponentRef;
    
    this
        .loader
        .loadIntoLocation(this.component, this.el, 'field')
        .then((res) => {
            componentRef = res;
            //Here it works
            componentRef.instance.setState("state");
        });