4

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?

1
  • The setName() function actually is: this.name = this.el.nativeElement.firstChild; Commented Mar 14, 2016 at 0:50

3 Answers 3

5

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);
  }
}
Sign up to request clarification or add additional context in comments.

Comments

2

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);
  }
}

Comments

0

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) {}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.