Open In App

Difference between directives and components

Last Updated : 17 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In Angular, directives, and components are essential concepts that help to build dynamic and interactive web applications. While they both play significant roles, understanding their differences and use cases is crucial for effective Angular development.

Directives

Directives in Angular are instructions in the DOM that tell Angular how to manipulate the behavior and appearance of elements. There are two types of directives: structural directives and attribute directives.

Syntax:

<div *ngIf="condition">Content to show when condition is true</div>

Angular provides two types of directives:

  • Structural Directives: These directives alter the DOM layout by adding, removing, or manipulating elements based on certain conditions. Examples include *ngIf, *ngFor, and *ngSwitch.
  • Attribute Directives: These directives modify the appearance or behavior of a DOM element. They are applied to elements as attributes. Examples include ngStyle, ngClass, and ngModel.

Features of Directives:

  • Directives modify the DOM based on certain conditions or criteria.
  • They can add, remove, or manipulate elements in the DOM.
  • Directives can be applied conditionally using structural directives like *ngIf and *ngFor.
  • Attribute directives modify the appearance or behavior of elements based on data or conditions.
  • Directives promote reusability and maintainability by encapsulating specific behavior.

Code Example:

To generate a new directive, we can use the following command.

ng generate directive upperCase
HTML
<!-- app.component.html -->

<form>
  <div>
    <label>Name: </label>
    <input
      appUpperCase
      type="text"
      name="name"
      minlength="4"
      [(ngModel)]="name"
      #nameInput="ngModel"
      required
      [ngClass]="{ 'is-invalid': nameInput.touched && nameInput.invalid }"
    />
    <div *ngIf="nameInput.touched && nameInput.invalid">
      Minimum length of name is 4 characters
    </div>
  </div>
  <div>
    <label>Age: </label>
    <input
      type="number"
      name="age"
      [(ngModel)]="age"
      #ageInput="ngModel"
      required
      [ngStyle]="{
        'border-color': ageInput.invalid && ageInput.touched ? 'red' : ''
      }"
    />
    <div *ngIf="ageInput.touched && ageInput.invalid">Age is required</div>
  </div>
</form>
JavaScript
//app.component.ts

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

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.scss'],
})
export class AppComponent {
    name: string = '';
    age!: number;
}
JavaScript
//upper-case.directive.ts

import { Directive, HostListener, ElementRef } from '@angular/core';

@Directive({
    selector: '[appUpperCase]',
})
export class UpperCaseDirective {
    constructor(private el: ElementRef) { }
    @HostListener('input')
    onInput(event: any) {
        const input = this.el.nativeElement.value.toUpperCase();
        this.el.nativeElement.value = input;
    }
}

Output:

Lightbox

Components

Components are the building blocks of Angular applications, comprising a template, class, and metadata. They encapsulate reusable UI elements and their associated logic.

A component comprises three main parts:

  • Template: Defines the HTML markup that represents the view of the component.
  • Class: Contains the logic and properties associated with the component.
  • Metadata: Specifies additional information about the component, such as its selector, styles, and dependencies.

Syntax:

@Component({
selector: 'app-example',
templateUrl: './example.component.html',
styleUrls: ['./example.component.css']
})
export class ExampleComponent {
// Component logic and properties
}

Features of Components:

  • Components encapsulate reusable UI elements along with their logic.
  • They have their own template, class, and metadata.
  • Components can communicate with other components using input and output properties.
  • They follow a hierarchical structure and can be nested within one another.
  • Lifecycle hooks allow developers to execute code at specific stages of a component’s lifecycle.

Code Example:

To create a new component in Angular use the following command.

ng generate component counter 
HTML
<!-- counter.component.html -->

<button (click)="increment()">
    Increment
</button>
<div>{{ count }}</div>
<button (click)="decrement()">
    Decrement
</button>
HTML
<!-- app.component.html -->

<div class="container">
    <h1>GeeksForGeeks</h1>
    <h3>
        Difference between Component and Module
    </h3>
    <app-counter> </app-counter>
</div>
JavaScript
//counter.component.ts
import { Component } from '@angular/core';

@Component({
    selector: 'app-counter',
    templateUrl: './counter.component.html',
    styleUrls: ['./counter.component.css'],
})
export class CounterComponent {
    count = 0;

    increment() {
        this.count++;
    }

    decrement() {
        this.count--;
    }
}
JavaScript
//app.component.ts

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

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css'],
})
export class AppComponent { }

Output:

Lightbox

Differences between Directives and Components

Aspect

Directives

Components

Definition

Instructions to manipulate the DOM or behavior of elements.

Building blocks encapsulating UI and logic.

Template

No template. Directives modify existing DOM elements.

Has a template defining the UI of the component.

Encapsulation

Can interact directly with the DOM.

Encapsulate their own UI and behavior.

Hierarchy

Not hierarchical.

Follows a hierarchical structure.

Reusability

Typically used for DOM manipulation.

Reusable UI elements with encapsulated logic.

Communication

Often used for DOM interaction and behavior modification.

Can communicate with other components via inputs and outputs.

Conclusion

In Angular development, directives and components serve distinct purposes but are both essential for building robust and interactive applications. Directives manipulate the DOM, while components encapsulate reusable UI elements and logic. Understanding the differences and use cases of directives and components is crucial for mastering Angular development and building efficient applications.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads