At Agira, Technology Simplified, Innovation Delivered, and Empowering Business is what we are passionate about. We always strive to build solutions that boost your productivity.

, ,

Components vs Directives in Angular with Examples

  • By Rajkumar M G
  • September 23, 2019
  • 17680 Views

Before we start with the differences between Components and Directives in Angular, let’s understand what is Components vs Directives in Angular. Ever since the release of angular, Components and Directives play a major role and acts as one of the key features. Let us now discuss how Components and Directives should be implemented. I suppose that you would know that these features are applicable only from Angular 2. And here is everything you need to know about Components Vs Directives in Angular with examples.

Components in Angular

Simply, Components is a UI control of the Applications. We know AngularJS is not Component-based. To optimize the design process, Components were introduced in Angular 2.

There are some major advantages when we go with Component-based like code reusability, enhance development speed and easy integration.
Basically, Component is a class. Decorator (@Component) makes its a component and provides configuration metadata. Component is a tree structure for the application. It interacts with HTML file and performs the data-bind. Components are a subset of directives.
The Syntax to create Component is given below.

ng generate component <component_name>  or ng g component <component_name>

Structure of Component

While creating component, Angular generates html, scss(css), spec.ts and ts(Typescript) files.
Following are the basics of the generated typescript files.

      /* Angular core library */
    import { Component, OnInit } from '@angular/core';
      /* Component declaration */
   @Component({
          selector:    'app-sample-page',     /* used to extends component in another component */
          templateUrl: './sample-page.component.html',     /* html page declaration */
          stylesUrls:  [ ‘./sample-page.component.scss’ ]   /* scss or css declaration */
    })
      /* class structure to do operations and functions */
   export class SamplePageComponent implements OnInit {
constructor() { } // constructor of a component class
 ngOnInit() {}  // lifecycle of angular component
   }

Note that any component that we create must be declared in App module or its respective modules. For instance, follow the code below.

       import { NgModule } from '@angular/core';
     import { SamplePageComponent } from './sample-page/sample.page.component;
     @NgModule({
              declarations: [SamplePageComponent]
     })
     export class SampleModule { }

Data Binding

Generally, without a framework, data related actions are done by HTML controls. Angular provides us two-way data binding mechanism to communicate with components and HTML templates.

Databinding
Image source: Angular website

The above diagram explains you how the data controls. Each form has a direction: to the DOM, from the DOM, or both
Here,

<app-sample-page  [myPropertyValue]=”PropertyBinding”      (eventControl)=”myEventController($event)”></app-sample-page>

In this, we injecting value through ‘myPropertyValue’ and handling the emitted value from ‘eventControl’. You can use @Input and @Output decorators to handle this data’s control.

Directives in Angular

Directives are simply the instructions in DOM. It specifies how to place your components and business logic in Angular. It is also a class. But, Decorator (@ Directive) makes it a Directive to stand out and perform its operations.
There are three types of Directives in Angular:

  1. Component Directive
  2. Structural Directive
  3. Attribute Directive

Component Directive

Component directive is used to specify the HTML templates. It has structure design and the working pattern of how the component should be processed, instantiated and used at runtime. It is the most commonly-used directive in any Angular project.
Above, we discussed the component, that should be the Component Directive.

  • sample-page.component.css: contains all the CSS styles for the component.
  • sample-page.component.html: contains all the HTML code used by the component to display itself.
  • sample-page.component.ts: contains all the code used by the component to control its behaviour.

Structural Directive

Structural Directive changes the DOM layout design and structure. The main usage of Structural Directive is for manipulating and making run-time changes on the DOM elements. You can easily recognize it by an asterisk (*) symbol.
Let’s consider a code for instance.

          <div *ngIf=”emp”> {{emp.name}} </div>
      <ul> 
            <li *ngFor=”let emp of Employees”> {{emp.name}} </li>
        </ul>
       <div [ngSwitch]="emp?.designation">
<app-emp-developer *ngSwitchCase="'developer'" [emp]=”emp”>       </app-emp-developer>
  <app-emp-tester  *ngSwitchCase="'tester'"  [emp]=”emp” "></app-emp-tester> 
      </div>

NgIf case study:

It is the simplest structure directive and easy to understand. Boolean expression can make entire DOM appear and disappear.

<p *ngIf=”true”> Expression true,makes entire DOM Appears.   </p>
<p *ngIf=”false”> Expression true,makes entire DOM Appears.  </p>

NgIf directive becomes property binding when you use it on <ng-template>.

<ng-template [ngIf]="emp">
  <div class="name">{{emp.name}}</div>
</ng-template>

NgFor case study:

It is like a loop. You can use an Array to iterate values. In addition, ngfor also becomes property binding when you use it on <ng-template>.

<div *ngFor="let emp of employees; let i=index; trackBy: trackById" >
  ({{i}}) {{emp.name}}
</div>
<ng-template ngFor let-hero [ngForOf]="heroes" let-i="index" let-odd="odd" [ngForTrackBy]="trackById">
  <div [class.odd]="odd">({{i}}) {{hero.name}}</div>
</ng-template>

Attribute Directive

An Attribute Directive changes the appearance or behaviour of a DOM element. However, it looks like a regular HTML attribute. In Attribute directive, we can easily implement it by simply specifying the selector. You can implement the directive behaviour on the controller class.
For instance, Let’s consider an example to change the text colour while hovering over the text, by using the attribute directive.

import { Directive, ElementRef, HostListener } from '@angular/core';
@Directive({
  selector: '[highlight-text]'
})
export class HighlightDirective {
  constructor(private el: ElementRef) { }
  @HostListener('mouseenter') onMouseEnter() {
        this.el.nativeElement.style.backgroundColor = ‘blue’;
  }
  @HostListener('mouseleave') onMouseLeave() {
     this.el.nativeElement.style.backgroundColor = ‘black’;
  }
}

You can use the directive in HTML elements through selector name as follows.

  <p highlight-text>Text to Highlight</p>

Angular provides a few attribute directives. Some of that are:
NgStyle: Depending on the component state, dynamic styles can be set by using NgStyle. Many inline styles can be set simultaneously by binding to NgStyle.
NgClass: It controls the appearance of elements by adding and removing CSS classes dynamically.
For instance, see the given code block.

<div *ngFor="let emp of employees;" >
  <p [ngStyle]=”{'color': emp.experience < 2 ? ‘blue’ :’black’}”>{{emp.name}}> </p>
</div>
<div *ngFor="let emp of employees;" >
  <p [ngClass]=”{‘cssClassA’: emp.experience < 2 , ‘cssClassB’: emp.experience >= 2 }”> {{emp.name}}> </p>
</div>

Hence, that’s the difference between Components vs Directives. Moreover, if you have any doubts about the above blog, do write it down in the comments.
Hire the best Angular developers in the industry in just a click. Find a skillful Angular developer for your business to get top-notch technology solutions for your company.

Are you looking for Angular developers to build your application? Here is the comprehensive guide on how to hire Angular developers. Also, it guides you with the following topics.

  • Angular developer skills.
  • How an ideal Angular developer resume should look.
  • Top Angular developer tools.
  • Commonly asked Angular developer interview questions.
  • Present Angular developer job opportunities.
Turn your vision to magnificent reality with
Our Web and Mobile Solutions

Moreover, you can read many other interesting blogs related to Angular. Such as Create Your First Custom Angular CLI Schematic With Nx and 6 Essential VSCode Extensions for Angular Developers.

Rajkumar M G

Around 3 years of experience in IT, Rajkumar evolving as a knowledge packed developer by expertising the technologies like JavaScript, AngularJS, Apache Cordova, Ionic, Java Spring MVC. And also extends his love on Robotic science & embedded system and trying to master it all.