📚

Guide to Angular Directives and Usage

Aug 11, 2024

Angular Built-in Directives and Custom Directives

Overview

  • Discussed built-in directives including ngIf, ngSwitch, ngClass, ngStyle, and ngFor.
  • Explanation of structural and attribute directives.
  • Introduction to building custom directives in Angular.

ngIf Directive

  • Used to show or hide parts of a page based on a condition.
  • Example: Displaying a list of courses or a 'no courses' message.
  • Syntax: <div *ngIf="courses.length > 0">List of courses</div> <div *ngIf="courses.length === 0">No courses yet</div>
  • Structural directive that modifies the DOM structure.
  • Angular 4 introduced an enhanced syntax using <ng-template> for ngIf with else.
  • Example with ng-template: <ng-template #noCourses>No courses yet</ng-template> <div *ngIf="courses.length > 0; else noCourses">List of courses</div>
  • Example with then and else: <ng-template #coursesList>List of courses</ng-template> <ng-template #noCourses>No courses yet</ng-template> <div *ngIf="courses.length > 0; then coursesList; else noCourses"></div>

hidden Attribute

  • Alternative to ngIf for showing and hiding elements.
  • Uses the hidden attribute to hide elements without removing them from the DOM.
  • Example: <div [hidden]="courses.length === 0">List of courses</div> <div [hidden]="courses.length > 0">No courses yet</div>
  • ngIf removes elements from the DOM, while hidden only hides them.
  • Suitable for large DOM trees or costly elements.

ngSwitch Directive

  • Similar to switch statements in programming languages.
  • Useful for comparing a value against multiple options.
  • Example for toggling views: <div [ngSwitch]="viewMode"> <div *ngSwitchCase="'map'">Map View Content</div> <div *ngSwitchCase="'list'">List View Content</div> <div *ngSwitchDefault>Other Content</div> </div>

ngFor Directive

  • Used for rendering a list of items.
  • Example: <ul> <li *ngFor="let course of courses">{{ course.name }}</li> </ul>
  • Exports various values like index, first, last, even, and odd.
  • Example of using index: <li *ngFor="let course of courses; let i = index">{{ i }} - {{ course.name }}</li>
  • Example of using even: <span *ngIf="isEven">Even</span>
  • Supports dynamic updates (adding, removing, or changing items).

Custom Directives

  • Introduction to creating custom directives in Angular.

Performance Considerations

  • ngIf is preferred for large DOM trees to free up resources.
  • hidden is better for costly DOM elements.

Conclusion

  • Summary of built-in directives and their usage.
  • Overview of upcoming topics such as change detection and performance.

Additional Resources

  • Reference to a complete Angular course with more in-depth content.