The biggest problem I have with Angular 1 is how difficult it is to extend (in the object-oriented sense) a directive.
For example, it is almost impossible to reuse the input[number]
directive on my a custom widget and I had to re-implement all the validation and type conversion code.
Angular 2 components are implemented as classes so it seems they can be easily extended. However, they also have that @Component
annotation with very specific selectors, etc., which makes it unclear to me if those can be fully overridden.
So are Angular 2 directives actually extensible?
Edit:
Okay, "extensible" does not have to be extending classes. It can be creating a new directive that is composed of multiple existing directives. My question with this approach is what is the mechanism to apply the child directives?
(The @Component
classes are not traditional OO classes with methods that one can dispatch to the children. It is only a container of fields and callbacks that are entirely driven by whatever is behind the annotation.)
Annotations are not inherited, so if you have:
@Directive({
selector:'foo',
inputs:['bar']
})
export class Foo {}
//no annotation
export class FooBar extends Foo {} //not a directive
@Directive({
selector:'foobaz'
})
export class FooBaz extends Foo {} //is a directive, but has no inputs
FooBar
will not be recognized as a directive at all, and FooBaz
will but it won't the bar
input (or any others). So, if inheritance is really what makes the most sense for your use-case, the way to approach this would be to declare inputs etc. in the child class annotations and pass them as constructor arguments to the parent class, where you can encapsulate common functionality.
That said, I don't think extensibility necessarily implies inheritance, and in my experience the old adage "favor composition over inheritance" is doubly true when DI is involved.
Someone much smarter than me recently said, "inheritance will murder your children in their sleep", and I tend to adhere to that viewpoint myself unless I'm damn sure it's the right tool for my use-case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With