Loading...

Directives in Angular

In Angular, directives are classes that add additional behavior to elements in your templates. They allow you to manipulate the DOM (Document Object Model), change the appearance of elements, and create reusable components.

Types of Directives

Angular has three main types of directives:

  1. Component Directives: Directives with a template. They are the most common type of directive and are used to create reusable UI components.
  2. Structural Directives: Directives that change the DOM layout by adding or removing elements.
  3. Attribute Directives: Directives that change the appearance or behavior of an element.

1. Component Directives

Component directives are the most powerful and versatile type of directive. They have their own templates and logic.

Example: Creating a Custom Component


    // custom-button.component.ts
    import { Component, Input } from '@angular/core';

                @Component({
                    selector: 'app-custom-button',
      template: `< button style = "background-color: {{buttonColor}}; color: white; padding: 10px;" & gt;
                        { { buttonText } }
                        </ button & gt;`
    })
    export class CustomButtonComponent {
                @Input() buttonText: string = 'Click Me';
                @Input() buttonColor: string = 'blue';
    }
    

Usage:


    <app-custom-button buttonText="Submit" buttonColor="green"></app-custom-button>
    

2. Structural Directives

Structural directives modify the DOM by adding or removing elements. Common structural directives include *ngIf, *ngFor, and *ngSwitch.

Example: *ngIf

The *ngIf directive conditionally adds or removes an element from the DOM.


    <p *ngIf="isVisible">This paragraph is visible.</p>
    

    // component.ts
    isVisible: boolean = true;
    

Example: *ngFor

The *ngFor directive iterates over a collection and renders a template for each item.


    <ul>
      <li *ngFor="let item of items">{{ item }}</li>
    </ul>
    

    // component.ts
    items: string[] = ['Apple', 'Banana', 'Orange'];
    

3. Attribute Directives

Attribute directives change the appearance or behavior of an element. Common attribute directives include [ngStyle], [ngClass], and custom attribute directives.

Example: [ngStyle]

The [ngStyle] directive allows you to dynamically apply inline styles.


    <p [ngStyle]="{'color': textColor, 'font-size': fontSize}">Styled Paragraph</p>
    

    // component.ts
    textColor: string = 'red';
    fontSize: string = '18px';
    

Example: [ngClass]

The [ngClass] directive allows you to dynamically add or remove CSS classes.


    <div [ngClass]="{'highlight': isHighlighted}">Styled Div</div>
    

    // component.ts
    isHighlighted: boolean = true;
    

If you have any questions, feel free to ask. Thank you for reading!

Thankyou!