-1

Any directives and pipes must be in module's declarations. Why can't they be added to component level and instead always have to be at module level? Why angular team has put this restriction?

Jyoti Prasad Pal
  • 1,569
  • 3
  • 26
  • 41
  • 1
    They were at the component level before modules existed, and believe me, it was quite painful to repeat the directives and pipes over and over again in every component. It just avoids many repetitions. – JB Nizet Aug 20 '17 at 10:31
  • I agree. However, if a pipe or directive to be used only by one component in module and not to be used by other components in the same module, it is not possible to restrict. – Jyoti Prasad Pal Aug 20 '17 at 10:48

1 Answers1

2

The Angular team talked about the reasons for deprecating component-level directives here when they introduced modules.

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.

There is nothing to stop you having a module that only exports a single component, which would allow you to scope any directives and pipes to that specific component, and this is more consistent and easier to reason about than having components effectively able to be their own modules in certain circumstances.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437