Skip to main content

Command Palette

Search for a command to run...

Activity 11: Research Angular Directives

Updated
•2 min read•View as Markdown

Angular Directives: Definition and Types

What Are Angular Directives?

Angular directives are special markers or instructions in the DOM that tell Angular to do something specific with an element or attribute. They help manipulate the DOM in a declarative way by enhancing the behavior or structure of elements in Angular applications.

Types of Directives in Angular:

  1. Component Directives:

    The most common type, these are essentially components themselves. A component directive is used to render a template, and its selector is typically defined as an HTML tag.

  2. Structural Directives:

    • Structural directives alter the structure of the DOM by adding or removing elements. They usually begin with an asterisk (*).

    • Examples: *ngIf, *ngFor, *ngSwitch

  3. Attribute Directives:

    • Attribute directives modify the appearance or behavior of an existing element. Unlike structural directives, they don’t change the DOM’s layout but change the element’s styling or behavior.

    • Examples: ngClass, ngStyle, ngModel

Use Cases of Angular Directives

  1. Component Directives

Use Case: Creating a reusable user interface component like a button or card layout. Component directives allow you to encapsulate reusable UI logic inside a custom HTML tag. For example, a <app-user-card> directive might be used to display user information consistently across your app.

Code Example:

  1. Structural Directives

Use Case: Conditional rendering or looping over a collection of items. Structural directives are great for manipulating the DOM based on dynamic conditions or iterations. *ngIf displays elements based on a condition, and *ngFor loops through an array to generate a list of items dynamically.

Code Example:

  1. Attribute Directives

Use Case: Dynamically applying classes or styles to elements. Attribute directives modify the behavior or appearance of an element. For example, ngClass and ngStyle are used to apply conditional styles or classes dynamically.

Code Example:

References:

https://angular.dev/guide/directives

https://www.tektutorialshub.com/angular/angular-directives/

https://www.tektutorialshub.com/angular/angular-directives/

https://www.digitalocean.com/community/tutorials/angular-ngif-directive

T

Good

8 days late