Skip to main content

Command Palette

Search for a command to run...

Activity 11: Research Angular Directives

Updated
4 min readView as Markdown
Activity 11: Research Angular Directives

Understand what Angular Directives:

Agular directives are markers on a DOM element (such as an attribute, element name, comment, or CSS class) that tell Angular to attach a specified behavior to that DOM element. They are a way of extending the functionality of HTML elements in Angular applications.

Three Types of Directives:

  • Component Directives: Component directives are used to create custom components in Angular. These components encapsulate the template, data, and behavior of a part of the user interface. They are typically used to break down the application into smaller, reusable parts.

  • Structural Directives (e.g., ngIf, ngFor): Structural directives are used to alter the structure of the DOM by adding, removing, or manipulating elements based on certain conditions. Examples of structural directives in Angular include *ngIf (conditionally showing/hiding elements) and *ngFor (repeating elements based on an iterable data source).

  • Attribute Directives (e.g., ngClass, ngStyle): Attribute directives are used to change the appearance or behavior of DOM elements. They are applied to elements as attributes. Examples of attribute directives in Angular include ngClass (to dynamically add or remove CSS classes based on conditions) and ngStyle (to dynamically set inline styles based on conditions).

  1. Use Cases of Angular Directives:

    1. Components Directives

    Components directives are the most common type of directive. They are essentially directives with a template. Components encapsulate the logic and view of a part of the UI.

    Use Case: Creating reusable UI elements.

    Example: A custom button component that can be reused across the application.

    TypeScript

    @Component({

    selector: 'app-custom-button',

    template: <button [ngClass]="btnClass">{{label}}</button>,

    styles: [`

    .primary { background-color: blue; color: white; }

    .secondary { background-color: gray; color: black; }

    `]

    })

    export class CustomButtonComponent {

    @Input() label: string;

    @Input() btnClass: string;

    }

    2. Attribute Directives

    Attribute directives change the appearance or behavior of an element, component, or another directive.

    Use Case: Applying conditional styles or behavior.

    Example: Using ngClass to conditionally apply CSS classes.

    HTML

    <p [ngClass]="{'highlight': isHighlighted, 'error': hasError}">This is a paragraph.</p>

    In this example, the highlight class is applied if isHighlighted is true, and the error class is applied if hasError is true.

    3. Structural Directives

    Structural directives change the DOM layout by adding and removing DOM elements.

    Use Case: Conditionally displaying elements.

    Example: Using *ngIf to conditionally display a section of the template.

    HTML

    <div *ngIf="isLoggedIn">

    <p>Welcome back, user!</p>

    </div>

    Here, the <div> element is only added to the DOM if isLoggedIn is true.

    Another common structural directive is *ngFor, which is used to iterate over a list and render a template for each item.

    HTML

    <ul>

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

    </ul>

    This will create a list item for each element in the items array.

  2. Search for Code Snippets:

    1. Conditional Rendering with *ngIf

    The *ngIf directive conditionally includes or excludes an element in the DOM based on a boolean expression.

    HTML

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

    In the above snippet, the paragraph will only be rendered if the isVisible variable is true.

    2. Looping with *ngFor

    The *ngFor directive is used to repeat a portion of the DOM tree for each item in a list.

    HTML

    <ul>

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

    </ul>

    Here, each item in the items array will be rendered as a list item (<li>).

    3. Dynamic Class Binding with ngClass

    The ngClass directive adds or removes CSS classes based on an expression.

    HTML

    <div [ngClass]="{ 'active': isActive, 'disabled': isDisabled }">

    This div's classes change dynamically.

    </div>

    In this example, the div will have the active class if isActive is true and the disabled class if isDisabled is true.

    4. Dynamic Style Binding with ngStyle

    The ngStyle directive dynamically sets one or more styles on an element.

    HTML

    <p [ngStyle]="{ 'color': isBlue ? 'blue' : 'red' }">

    This text changes color based on the isBlue variable.

    </p>

    Here, the text color will be blue if isBlue is true, otherwise it will be red.

    5. Custom Attribute Directive

    You can also create custom attribute directives to encapsulate common behavior.

    TypeScript

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

    @Directive({

    selector: '[appHighlight]'

    })

    export class HighlightDirective {

    constructor(private el: ElementRef, private renderer: Renderer2) {}

    @HostListener('mouseenter') onMouseEnter() {

    this.highlight('yellow');

    }

    @HostListener('mouseleave') onMouseLeave() {

    this.highlight(null);

    }

    private highlight(color: string) {

    this.renderer.setStyle(this.el.nativeElement, 'backgroundColor', color);

    }

    }

    In this custom directive, the background color of the element will change to yellow when the mouse enters and revert when the mouse leaves.

Reference:

Exploring Angular Directives: A Comprehensive Guide - DEV Community

Built-in directives in Angular - GeeksforGeeks

Directives in Angular: A Beginner’s Guide | by dalanda drissi | Medium

https://angular.dev/guide/directives/

T

use /code sa hashbode -5

More from this blog

Darsie

30 posts