Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are Angular 2 directives now "extensible"?

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.)

like image 851
billc.cn Avatar asked Dec 16 '15 11:12

billc.cn


1 Answers

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.

like image 140
drew moore Avatar answered Nov 15 '22 09:11

drew moore