Danilo Azevedo
Danilo Azevedo

Reputation: 243

TypeScript function inheritance

I don't even know if this is possible in TypeScript, but I'm trying to inherit a function from a Class, like this:

import {Component, AfterViewInit, ElementRef} from 'angular2/core';

@Component({})
class Class1 {
  name: string;
  constructor(private el: ElementRef) {}

  private setName() {
    this.name = "test";
  }

  ngAfterViewInit() {
    this.setName();
  }
}

@Component({
  selector: 'test'
})
export class Class2 extends Class1 {
  ngAfterViewInit() {
    super.ngAfterViewInit();
    console.log(this.name);
  }
}

but I'm getting the following error in console when calling the setName() function:

EXCEPTION: TypeError: this.el is undefined

Why isn't this working?

Upvotes: 4

Views: 5888

Answers (3)

basarat
basarat

Reputation: 276085

Constructors are not inherited.

They are. Following sample shows this:

class Parent {  
    constructor(foo:number){}
}
class Child extends Parent {    
}

const child1 = new Child(); // Error!
const child2 = new Child(123); // OKAY!  

But this is angular

However they are not analyzed for dependency injection. This means that your child class constructor isn't called with the same parameters as expected by the parent (in your case `el). You need to specify all the DI elements on each child class. So by chance the correct code is the one from the accepted answer:

@Component({
  selector: 'test'
})
export class Class2 extends Class1 {
  constructor(el: ElementRef) {
    super(el);
  }
}

Upvotes: 5

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657731

Constructors are not inherited. You need to define them in each subclass

@Component({
  selector: 'test'
})
export class Class2 extends Class1 {
  constructor(el: ElementRef) {
    super(el);
  }

  ngAfterViewInit() {
    super.ngAfterViewInit();
    console.log(this.name);
  }
}

Upvotes: 2

bcherny
bcherny

Reputation: 3172

Consider updating el's scope to protected, meaning it can be accessed by both the class where it's declared and any derived classes.

// before
constructor(private el: ElementRef) {}

// after
constructor(protected el: ElementRef) {}

Upvotes: 0

Related Questions