Skip to main content

Command Palette

Search for a command to run...

Activity 12: Research Angular Directives

Updated
2 min readView as Markdown
Activity 12: Research Angular Directives
  1. Research the Definition of Angular Directives:

    → a function that executes when found in the DOM by the Angular compiler to extend the power of the HTML with new syntax.

  • Components Directives Used with a template. This type of directive is the most common directive type.

  • Structural Directives are directives which change the DOM layout by adding and removing DOM elements. Angular provides a set of built-in structural directives (such as NgIf, NgForOf, NgSwitch and others) which are commonly used in all Angular projects.

  • Attribute Directives are a fundamental building block for extending and customizing the behavior of components in Angular applications. The ngstyle directive can be used to set styles by assigning an object to it. ngClass By dynamically adding and removing CSS classes it manages the appearance of elements.

  1. Use Cases of Angular Directives:

Component Directives:

  • Creating reusable UI elements, Encapsulating complex logic,Managing state

Structural Directives:

  • Conditional Rendering,Iteration,Dynamic Template Creation

Attribute Directives:

  • Styling,Validation,Behavior Modification

Directives may dramatically improve the behavior and organization of DOM components in Angular applications. Using both built in and custom directives, developers may construct dynamic, interactive, and user friendly online experiences.

  1. Search for Code Snippets:

    Looping with *ngFor:

<ul>
    <li *ngFor="let product of products">
        {{product.name}} - ${{product.price}}
    </li>
</ul>

The *ngFor directive iterates over the products array, generating a element for each product and dynamically displays the name and price.

Conditional Rendering with *ngIf:

<div *ngIf="isLoggedIn">
    Welcome, {{username}}!
</div>

The *ngIf directive renders the element only when the isLoggedIn value is true, delivering a personalized welcome message with the user's name.

Dynamic Class Binding with ngClass:

<button [ngClass]="{ 'active': isActive, 'disabled': isDisabled }">Click Me</button>

The ngClass directive dynamically adds CSS classes to the element based on the values of isActive and isDisabled, modifying its look appropriately.

  1. Document Your Research on Hashnode:

https://v17.angular.io/guide/structural-directives

More from this blog

Untitled Publication

66 posts