What are the main differences between components and directives in AngularJS 1.5?

Martin picture Martin · Jul 13, 2016 · Viewed 27.3k times · Source

I am finding it difficult to understand the real difference between components and directives. I now understand that components are a much easier concept.

So having this in mind, is there any reason to continue to use directives when using AngularJS 1.5?

Maybe I am missing the real context here, but it appears that components provide an easier API.

So what reason would I have to continue using a directive?

Angular 2 states that everything is a component, so working towards an easy migration from 1.5 to 2, would it not make sense to only use components going forward?

In the past I have used directives for creating, for example, an auto lookup textbox, there is no reason why I shouldn't do this now inside a component right? And then I can re-use this component inside other components I create?

Answer

bresleveloper picture bresleveloper · Jul 13, 2016

Just copying the angular docs, since they put it in the best way I can think.

Understanding Components

In Angular, a Component is a special kind of directive that uses a simpler configuration which is suitable for a component-based application structure.

This makes it easier to write an app in a way that's similar to using Web Components or using Angular 2's style of application architecture.

Advantages of Components:

  • simpler configuration than plain directives
  • promote sane defaults and best practices
  • optimized for component-based architecture
  • writing component directives will make it easier to upgrade to Angular 2

When not to use Components:

  • for directives that rely on DOM manipulation, adding event listeners etc, because the compile and link functions are unavailable
  • when you need advanced directive definition options like priority, terminal, multi-element
  • when you want a directive that is triggered by an attribute or CSS class, rather than an element

more reading:https://docs.angularjs.org/guide/component