ps0604
ps0604

Reputation: 1071

Inheriting components in Angular 2+

Is it OK to inherit @Component classes in Angular 2+ ? Something like this (note that the constructors will inject a service):

@Component({})
export class Parent {
    constructor ( s0: Service1 ) {}
}

@Component({
     template: 'text1'
})
export class Child1 extends Parent {
    constructor ( s1: Service1 ) { super(s1); }
}

@Component({
     template: 'text2'
})
export class Child2 extends Parent {
    constructor ( s2: Service1 ) { super(s2); }
}

Upvotes: 1

Views: 31

Answers (1)

Igor
Igor

Reputation: 62213

Sure although you might want to mark type Parent as abstract and remove @Component as the decorator on that type as well.

export abstract class Parent {
    constructor (protected s0: Service1 ) {}
}

I also marked s0 as protected so it is accessible in derived types

Upvotes: 2

Related Questions