Angular Directives


Definition of Angular Directives

Angular directives are special markers on a DOM element (such as an attribute, element name, or comment) that tell Angular to attach a specified behavior to that DOM element or transform the DOM element and its children.

There are three types of directives in Angular:

  • Component Directives: These are the most common type of directive and are used to define a custom UI component. A component directive contains the HTML template, the business logic, and its own encapsulated scope.

  • Structural Directives (e.g., ngIf, ngFor)*:* These directives modify the DOM by adding or removing elements based on conditions or loops.

  • Attribute Directives (e.g., ngClass, ngStyle): These change the appearance or behavior of an element, component, or another directive. Attribute directives deal with styling or modifying elements based on conditions.


Use Cases of Angular Directives

  • Component Directives: Used to create reusable UI components that encapsulate their structure and logic. For example, a custom button or card component.

  • Structural Directives: Modify the layout of the DOM by conditionally adding, removing, or repeating elements. For example, *ngIf is used to conditionally render an element, and *ngFor is used to loop over a list of items and generate elements for each item.

    • Example:

      • *ngIf: Used for conditional rendering.

      • *ngFor: Used for creating lists or tables.


Code Snippets

Component Directives:
@Component({
selector: 'app-custom-button',
template: '{{label}}',
styles: ['button { color: blue; }']
})
export class CustomButtonComponent {
@Input() label: string = 'Click me';
}

Structural Directives:

  • *ngIf Example:

    <div *ngIf="isLoggedIn">Welcome, User!</div>

  • *ngFor Example:

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

Attribute Directives:

  • ngClass Example:

    <div [ngClass]="{'active': isActive}">Active Content</div>

  • ngStyle Example:

    <div [ngStyle]="{'color': textColor}">Styled Text</div>


REFERENCES:

Official Angular Documentation on Directives: https://angular.io/guide/built-in-directives

Angular University Blog on Directives: https://blog.angular-university.io/angular-directives/

11
Subscribe to my newsletter

Read articles from Walter Mark B. Inductivo Jr. directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Walter Mark B. Inductivo Jr.
Walter Mark B. Inductivo Jr.

Watch Me Whip ๐Ÿ‘Š, Watch Me Nae-Nae ๐Ÿ–๏ธ