Difference between directive and component |
In this post, we will see the difference between directive and component in Angular?
Directives
In short, you can say that directives define functionality, mostly to manipulate the HTML DOM, it doesn’t define any UI. You attach the directive to an existing view or template. On the other hand, components define view or template as well as the logic to manipulate the template.
Basically, there are three types of directives in angular as per the documentation.
- Component
- Structural directives
- Attribute directives
Component
Component decorator allows you to mark a class as an Angular component and provide additional metadata that determines how the component should be processed, instantiated and used at runtime.
Components are the most basic building block of a UI in an Angular application. An Angular application is a tree of Angular components. Angular components are a subset of directives. Unlike directives, components always have a template and only one component can be instantiated per an element in a template.
A component must belong to a NgModule in order for it to be usable by another component or application. To specify that a component is a member of a NgModule, you should list it in the declarations field of that NgModule.
is also a type of directive with template, styles and logic part which is the most famous type of directive among all in angular.
In this type of directive you can use other directives whether it is custom or built-in in the @component annotation like following:
@Component({
selector: "my-app"
directives: [custom_directive_here]
})
use this directive in your view as:
<my-app></my-app>
Structural directives
like *ngFor and *ngIf used for changes the DOM layout by adding and removing DOM elements.
Attribute directives
are used to give custom behavior or style to the existing elements by applying some functions/logic. like ngStyle is an attribute directive to give style dynamically to the elements. we can create our own directive and use this as Attribute of some predefined or custom elements, here is the example of a simple directive:
firstly we have to import directive from angular2/core
import {Directive, ElementRef, Renderer, Input} from 'angular2/core';
@Directive({
selector: '[Icheck]',
})
export class RadioCheckbox {
custom logic here,,,,
}
and we have to use this in the view like below:
<span Icheck>HEllo Directive</span>