Angular 2 指令现在“可扩展"了吗? [英] Are Angular 2 directives now "extensible"?

查看:22
本文介绍了Angular 2 指令现在“可扩展"了吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Angular 1 中遇到的最大问题是扩展(在面向对象的意义上)指令有多么困难.

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

例如,几乎不可能在我的自定义小部件上重用 input[number] 指令,我不得不重新实现所有验证和类型转换代码.

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 组件是作为类实现的,因此它们似乎可以轻松扩展.但是,他们也有带有非常具体的选择器等的 @Component 注释,这让我不清楚这些是否可以完全覆盖.

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.

那么 Angular 2 指令实际上是可扩展的吗?

So are Angular 2 directives actually extensible?

好的,可扩展"不一定是扩展类.它可以创建一个由多个现有指令组成的新指令.我对这种方法的问题是应用子指令的机制是什么?

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?

(@Component 类不是传统的 OO 类,其方法可以分派给子级.它只是一个包含完全由注释背后的内容驱动的字段和回调的容器.)

(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 根本不会被识别为指令,并且 FooBaz 会但它不会是 bar 输入(或任何其他).因此,如果继承真的对您的用例最有意义,那么解决此问题的方法是在子类注释中声明输入等并传递它们作为父类的构造函数参数,您可以在其中封装通用功能.

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.

也就是说,我认为可扩展性不一定意味着继承,根据我的经验,当涉及到 DI 时,古老的格言喜欢组合而不是继承"是双重正确的.

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.

这篇关于Angular 2 指令现在“可扩展"了吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆