为什么所有指令和管道都必须在模块的声明中?
Why all Directives and Pipes must be in module's declarations?
任何指令和管道都必须在模块的声明中。为什么不能将它们添加到组件级别而总是必须在模块级别?为什么 angular 团队设置了这个限制?
Angular 团队在引入模块时讨论了弃用组件级指令的原因 here。
Deprecation
The ability to import directives and pipes into components will be
deprecated. This means that after deprecation the following properties
will be removed: @Component.directives
and @Component.pipes
.
Why
Keeping @Component.directives
/pipes
causes the following issues:
Two Scopes
It creates two scopes: module scope and component scoped. The module
scoped is very similar to how ES6 modules work. As a result, it is
easy to explain to the user. We have to have it for dev ergonomics.
The component scope is unique and harder to explain.
Breaks ES6 Mental Model
Having the component scope breaks the ES6 mental model. In ES6 to use
a token you have to import it from a module. Tokens don't just appear
out of nowhere. It is easy to explain that to use a material component
you need to import the right module. Because that's what you would do
with ES6.
Nobody Will Use It
Modules create small-enough scope to avoid collisions, and they are
significantly more ergonomic. Because using modules is more ergonomic,
the Component.directives
option will not be used in practice. As a
new Angular user I have to use modules to get my forms and common
directives, so it is natural for me to add my own directives there.
没有什么可以阻止你拥有一个只有 exports
单个组件的模块,这将允许你将任何指令和管道的范围限定到该特定组件,并且这更加一致且更容易推理而不是在某些情况下让组件有效地成为它们自己的模块。
任何指令和管道都必须在模块的声明中。为什么不能将它们添加到组件级别而总是必须在模块级别?为什么 angular 团队设置了这个限制?
Angular 团队在引入模块时讨论了弃用组件级指令的原因 here。
Deprecation
The ability to import directives and pipes into components will be deprecated. This means that after deprecation the following properties will be removed:
@Component.directives
and@Component.pipes
.Why
Keeping
@Component.directives
/pipes
causes the following issues:Two Scopes
It creates two scopes: module scope and component scoped. The module scoped is very similar to how ES6 modules work. As a result, it is easy to explain to the user. We have to have it for dev ergonomics. The component scope is unique and harder to explain.
Breaks ES6 Mental Model
Having the component scope breaks the ES6 mental model. In ES6 to use a token you have to import it from a module. Tokens don't just appear out of nowhere. It is easy to explain that to use a material component you need to import the right module. Because that's what you would do with ES6.
Nobody Will Use It
Modules create small-enough scope to avoid collisions, and they are significantly more ergonomic. Because using modules is more ergonomic, the
Component.directives
option will not be used in practice. As a new Angular user I have to use modules to get my forms and common directives, so it is natural for me to add my own directives there.
没有什么可以阻止你拥有一个只有 exports
单个组件的模块,这将允许你将任何指令和管道的范围限定到该特定组件,并且这更加一致且更容易推理而不是在某些情况下让组件有效地成为它们自己的模块。