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?
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?
Share Improve this question asked Mar 14, 2016 at 0:47 Danilo AzevedoDanilo Azevedo 3431 gold badge4 silver badges10 bronze badges 1-
The setName() function actually is:
this.name = this.el.nativeElement.firstChild;
– Danilo Azevedo Commented Mar 14, 2016 at 0:50
3 Answers
Reset to default 5Constructors 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);
}
}
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);
}
}
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) {}