Search code examples
angularangular2-directivesangular2-pipe

Why all Directives and Pipes must be in module's declarations?


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?


Solution

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