Are Angular 2 directives now "extensible"?

The biggest problem with Angular 1 is how difficult it is to extend (in an object-oriented sense) the directive.

For example, it is almost impossible to reuse the input[number] directive for my custom widget, and I had to re-implement all the type checking and conversion code.

Angular 2 components are implemented as classes, so it seems that they can be easily extended. However, they also have @Component annotation with very specific selectors, etc., which makes it unclear to me if they can be completely redefined.

So, are Angular 2 directives extensible?

Edit:

Well, extensible doesn't have to extend classes. He can create a new directive consisting of several existing directives. My question with this approach is what is the mechanism for applying child directives?

(The @Component classes @Component not traditional OO classes with methods that you can send to children. It is just a container of fields and callbacks, completely controlled by what is behind the annotation.)

+5
source share
1 answer

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 will not be the input of bar (or any other). So, if inheritance is really what makes the most sense for your use case, a way to get closer to this would be to declare input, etc. In annotations of the child class and passing them as constructor arguments to the parent of the class, where you can encapsulate the general functionality.

However, I do not think that extensibility necessarily implies inheritance, and, in my experience, the old adage “prefers composition over inheritance” is doubly true when DI is involved.

Someone who was much smarter than me recently said: “Inheritance will kill your children in a dream,” and I tend to stick to this point of view if I'm not sure if this is the right tool for my use case.

+5
source

Source: https://habr.com/ru/post/1238375/


All Articles