Difference between Directive and Component in AngularJS

16 Jun, 2020
Introduction:We will start this topic of finding the differences between Directive and Components, by getting a brief idea about these two terminologies, what they mean, and their behavioral characteristics towards building a crisp, and powerful AnglarJS code. Directives are introduced with the invention of Angular, as a structural framework for building dynamic web applications. Directives were popular in manipulating the DOM i.e. Document Object Model and create new custom elements that were part of the DOM. With the upgrade in technology and various modifications in the later versions of Angular(Angular 2 and higher versions, as Angular 2 is itself dependent on the component-based structure) the use of Components is now seen with great interest among the developers. Also, Components are termed as a more simplified version of Directives.
Basic definitions:Directives are functions that are invoked whenever AngularJs’s HTML compiler($compile) finds it in DOM. It tells to attach a specified behavior to that DOM element (e.g. via event listeners), or even to transform the DOM element and its children.Components are just a simplified version of a directive. More specifically Components can be called a special kind of directives with templates, which are mainly used for component-based architecture.Examples:
Component-Syntax:import {Component, View} from 'angular2/angular2';
@Component ({........
            ........ })
@View ({............
         ...........})import {Component, View} from 'angular2/angular2';@Component({  selector: 'message'})@View({  template: `      <h6>Hello GeeksforGeeks</h6>      <h6>This is an example of component</h6> `})class Message {  constructor(public version: string) {}}Output:Hello GeeksforGeeks
This is an example of component
import {Component, View} from 'angular2/angular2';
@Component ({........
            ........ })
@View ({............
         ...........})
import {Component, View} from 'angular2/angular2';@Component({  selector: 'message'})@View({  template: `      <h6>Hello GeeksforGeeks</h6>      <h6>This is an example of component</h6> `})class Message {  constructor(public version: string) {}}
Output:
Hello GeeksforGeeks
This is an example of component
Directive-Syntax:import {Directive} from 'angular2/angular2';
@Directive({........
            ........})import {Directive} from 'angular2/angular2';  @Directive({    selector: "[myDirective]",    hostListeners: {        'click': 'showMessage()'    }})class Message {      constructor() {}      showMessage() {     console.log('This is an example of directive'); }}  <button>GeeksforGeeks</button>Output:Geeksforgeeks
This is an example of directive
import {Directive} from 'angular2/angular2';
@Directive({........
            ........})
import {Directive} from 'angular2/angular2';  @Directive({    selector: "[myDirective]",    hostListeners: {        'click': 'showMessage()'    }})class Message {      constructor() {}      showMessage() {     console.log('This is an example of directive'); }}  <button>GeeksforGeeks</button>
Output:
Geeksforgeeks
This is an example of directive
Explanation:In the above examples, we have seen how to write simple Angular code for printing some messages, both using Component, and Directive. In the Component’s example, we have seen that it is mandatory to write view property, whereas, for Directives, we do not need to use view or templates. Let us now discuss what are the main differences between these two.Differences:
A component is always elements (‘E’) where directive can be an attribute, element name, comment or CSS class (‘E’, ‘A’, ‘C’, ‘M’). Templates are the mandatory property and always required in Component, but Directive doesn’t always require them.Component is used to break up the application into smaller components. But Directive is used to design re-usable components, which is more behavior-oriented. That is why components are widely used in later versions of Angular to make things easy and build a total component-based model.As Component has views, viewEncapsulation can be defined. Whereas Directive doesn’t have views. So you can’t use viewEncapsulation in directive.Although Components make it easier to write simple, effective code, it has a simpler configuration than plain directives, it is optimized for component-based architecture. But when not to use a component? The answer is – a component does not support “compile” and “pre-link” functions. So for manipulating DOM objects, we should use the directives.
A component is always elements (‘E’) where directive can be an attribute, element name, comment or CSS class (‘E’, ‘A’, ‘C’, ‘M’). Templates are the mandatory property and always required in Component, but Directive doesn’t always require them.
Component is used to break up the application into smaller components. But Directive is used to design re-usable components, which is more behavior-oriented. That is why components are widely used in later versions of Angular to make things easy and build a total component-based model.
As Component has views, viewEncapsulation can be defined. Whereas Directive doesn’t have views. So you can’t use viewEncapsulation in directive.
Although Components make it easier to write simple, effective code, it has a simpler configuration than plain directives, it is optimized for component-based architecture. But when not to use a component? The answer is – a component does not support “compile” and “pre-link” functions. So for manipulating DOM objects, we should use the directives.
Components should never modify any data or DOM that is out of their own scope. Directives have isolated scopes, by default the child inherits the scope from its parent.
Only one component can be present per DOM element. There can be more than one directive in a DOM element
To register component we use @Component meta-data annotation. For directive, we use @Directive meta-data annotation. Two simple examples are shown in the point ‘Example’ above.
Conclusion:A basic study on the topic has been given. Whether to use Component or Directive, it totally depends on the purpose of writing a particular code for the usage. With the advent of emerging technologies, most of the web page design architectures are aiming towards obtaining a component-based model and this is when we need Components. On the other hand, directives give us plenty of options as selectors, input, output, providers to write the code creatively.
AngularJS-Directives
Picked
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Auth Guards in Angular 9/10/11
Routing in Angular 9/10
What is AOT and JIT Compiler in Angular ?
Angular PrimeNG Dropdown Component
How to set focus on input field automatically on page load in AngularJS ?
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?