I have a module in Angular that is structured likes this:
moduleName
componentA
componentB
Now componentA
and componentB
are very similar, as they share some attributes and methods, e.g.:
protected available: boolean = true;
As I don't want to repeat myself, I've created a base class, that stores all this:
export abstract class BaseComponent {
protected available: boolean = true;
}
And both controllers inherit from that class:
import { BaseComponent } from '../base.component';
export class ComponentA extends BaseComponent implements OnInit {
constructor() {
super();
}
ngOnInit() {
console.log(this.available);
}
}
This works just fine. However, when I research this soultion a lot of people are saying:
Don't use inheritance, use composition in this case.
Alright, but how can I use composition instead? And is the gain really that big over the current solution?
Thanks a lot for your time.
validator = new Validator()
and later dovalidator.check(input)
in many classes. As opposed to each class extendingValidator
and inheriting thecheck()
functionality. – InotropicserviceName.available
to access a property. But the advantage is, that the service is coupled more loosely, right? And a service is not necessarily global in Angular - I mean: the injected services are all individual instances for their component, correct? @KirkLarkin – Laud