Are Angular 2 directives now “extensible”?

一曲冷凌霜 提交于 2019-12-10 14:43:15

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/34310966/are-angular-2-directives-now-extensible

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!