Angular 2指令现在是否“可扩展"? [英] Are Angular 2 directives now "extensible"?
问题描述
我对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屋!