Skip to main content

Angular 2: Difference between Component and Directive

Putting it straight:

When any ordinary class is decorated with @Directive decorator it becomes a directive. Directives can be used to extend beviour of html elements. There are three types of directives

  • Component Directive
  • Structural Directive
  • Attribute Directive
It means that Component is a type of directive, and since it is a very important type and central piece in angular based applications, angular team has provided a separate decorator "@Component" for it. 



import {Directive} from '@angular/core';

@Directive({
    selector: "[disableOnClick]",
})
class DisableOnClick {
    @HostListener('click', ['$event.target'])
    onClick(element) {
        element.disabled= "disabled"
    }
}

The above directive can be used by any element like so:

<button disableOnClick></button>
On the other hand Components basically extend your applications HTML vocabulary by creating new reusable elements throughout the application.

@Component({
  selector: 'welcome',
  template: `
    <div>
      <p>Welcome {{username}}</p>
    </div>
  `
}) export class WelcomeComponent implements OnInit {
  @Input() username: string
  constructor() {}
}
And this component can be used anywhere in your application like so:

<welcome disableOnClick></welcome>
For further reading please check following links at angular.io 

Introduction to components
Directives

Comments