Angular Directives

Built-in Directives

ngIf: This directive conditionally adds or removes elements from the DOM based on the evaluation of an expression.

                          
                          <div *ngIf="showElement">This element is shown conditionally</div>
                     
                          
                        

ngFor: This directive iterates over a list and generates HTML for each item in the list.

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

                          
                        

ngSwitch: This instruction is the same as that of switch statement in JavaScript and thus it can be employed to determine what to display on specific cases.

                          
<div [ngSwitch]="color">
  <div *ngSwitchCase="'red'">Red color</div>
  <div *ngSwitchCase="'blue'">Blue color</div>
  <div *ngSwitchDefault>Other color</div>
</div>

                          
                        

Creating Custom Directives

Simultaneously with the built-in directives, you can also create custom directives to wrap and pass around the behavior throughout the application; this includes the directives of your program.

Here's how you can create a basic custom directive:

  • Generate Directive: Use the Angular CLI command ng generate directive directiveName or its shorthand ng g d directiveName to generate a new directive.
  • Directive Class: This is a TypeScript class that contains the logic for the directive. It typically includes methods and properties that define the directive's behavior.
  • Directive Decorator: Instruction of the directive is wrapped with the decorator @Directive() as which you can add a specimen for, for instance, the selector or any input or output property.
  • Directive Logic: Initialize the directive's behavior as with its class.
                          
import { Directive, ElementRef } from '@angular/core';

@Directive({
  selector: '[appHighlight]'
})
export class HighlightDirective {
  constructor(private el: ElementRef) {
    el.nativeElement.style.backgroundColor = 'yellow';
  }
}

                          
                        

You can then use your custom directive in templates like this:

                          
                          <p appHighlight>Highlighted text</p>