I have just started working with Angular 2.
I was wondering what are the differences between components and directives in Angular 2?
A component is a single unit that encapsulates both view and logic whereas directives are used to enhance the behavior of components or dom elements and it doesn't have any templates.
by putting brackets around the selector, that informs Angular of how it can be used. in this case [nbMenuItem] means this can be use as an attribute of a DOM element, and as such as an directive. Nailed the answer!
Directive is an attribute <tag attribute></tag> in your tags (components) and a service is a functionality that you can replicate in several views (Methods, Values, etc) in your app.
The Component is a fundamental block of Angular and multiple components will make up your application. A module can be a library for another module. For instance, the angular2/core library which is a primary Angular library module will be imported by another component.
Basically there are three types of directives in Angular2 according to documentation.
It is also a type of directive with template,styles and logic part which is most famous type of directive among all in Angular2. In this type of directive you can use other directives whether it is custom or builtin 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>
For the component directive i have found best tutorial here.
Like *ngFor
and *ngIf
, used to change the DOM layout by adding and removing DOM elements. explained here
They 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 @angular/core
import {Directive, ElementRef, Renderer, Input} from '@angular/core'; @Directive({ selector: '[Icheck]', }) export class RadioCheckbox { // custom logic here... }
We can use this in the view as shown below:
<span Icheck>HEllo Directive</span>
For more info you can read the official tutorial here and here
Components have their own view (HTML and styles). Directives are just "behavior" added to existing elements and components.Component
extends Directive
.
Because of that there can only be one component on a host element, but multiple directives.
Structural directives are directives applied to <template>
elements and used to add/remove content (stamp the template). The *
in directive applications like *ngIf
causes a <template>
tag to be created implicitly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With