Wednesday, July 26, 2023

Angular - How to create custom structural directive?

Angular custom structural directive

Creating a custom structural directive in Angular allows you to modify the DOM based on certain conditions, extending the template syntax. Structural directives are identified by the asterisk (*) preceding the directive name in the HTML template. Let's go through the steps to create your own custom structural directive in Angular.

Step 1: Set up the Angular project: Ensure that you have Angular CLI installed. If not, you can install it using npm:
npm install -g @angular/cli
Create a new Angular project:
ng new custom-structural-directive-demo
cd custom-structural-directive-demo
Step 2: Generate the directive: Next, generate a new directive using Angular CLI:
ng generate directive customIf

This generates a new directive file named 'custom-if.directive.ts' in the 'src/app' folder.

Monday, July 24, 2023

Angular - An Introduction to Structural Directives in Angular

Angular structural directive

In post Directive in Angular, we tried to understand what is directive? In this post, we'll explore Structural Directives and understand how they enhance the functionality and flexibility of Angular applications.

What are Structural Directives?

Structural Directives in Angular are a type of directive that modify the layout and structure of the DOM by adding or removing elements based on conditions. Unlike Attribute Directives, which change an element's behavior or appearance, Structural Directives directly impact the DOM's structure. The most commonly used Structural Directives in Angular are 'ngIf', 'ngFor', and 'ngSwitch'.

1. ngIf: The 'ngIf' directive conditionally adds or removes an element from the DOM based on the evaluation of an expression. It proves particularly useful when you need to show or hide specific parts of your template depending on your application's state. Example:
<ng-container *ngIf="isLoggedIn">
  <p>Welcome, {{ username }}!</p>
</ng-container>
In this example, the '<p>' element will only be rendered if the 'isLoggedIn' variable is true.

Thursday, July 20, 2023

Angular - Understanding Directives in Angular

Angular directives

Angular is a widely used front-end framework known for its ability to create dynamic web applications. One of its essential features is directives, enabling developers to extend HTML and build reusable components with customized behavior and functionality. In this post, we'll deep dive into what directives are, the various types available in Angular, and how to utilize them efficiently in your projects.

What are Directives?

In Angular, directives serve as markers on DOM elements, instructing Angular's compiler to attach specific behavior or functionality to those elements. They are instrumental in manipulating the DOM, adding or modifying elements, applying styles, handling events, and more. By using directives, you can extend HTML with your own custom attributes or tags, making your code more expressive and easier to maintain.

Types of Directives in Angular

Angular provides three primary types of directives:

  1. Component Directives: Components are the most commonly used type of directive. They are essentially directives that come with an associated template. Components encapsulate the template, styles, and behavior of a specific part of the user interface, acting as reusable building blocks throughout your application.
  2. Attribute Directives: Attribute directives modify the behavior or appearance of existing elements or components. They are used as attributes on elements and are denoted by square brackets, such as '[ngStyle]' or '[ngClass]'. Attribute directives are useful for applying conditional styles, enabling/disabling elements, or performing other transformations on elements.
  3. Structural Directives: Structural directives modify the DOM's structure by adding or removing elements. They are also used as attributes but are denoted by an asterisk ('*') before the directive name. Some examples include '*ngIf', '*ngFor', and '*ngSwitch'. These directives are commonly employed for rendering lists, conditionally displaying content, and handling template rendering.

Monday, June 5, 2023

Angular Trackby to improve ngFor Performance

Angular Trackby to improve ngFor Performance

Do you utilize ngFor in Angular to iterate over arrays or collections? If that's the case, you might have come across performance issues or unexpected behavior when updating or deleting items. But fret not! Angular offers a practical solution known as trackBy that can greatly enhance the performance and stability of your ngFor loops. Let's delve into it and learn how to effectively use it.


The Challenge

By default, Angular employs the index of each item in an array to track changes in ngFor loops. This implies that if the array's order changes or items are added or removed, Angular will re-render the entire list. Such a scenario can lead to performance bottlenecks, particularly when dealing with large arrays or complex components within the loop.

The following example shows what happens when we refresh the entire list. The App displays the list of names. it has option to add a name, remove a name and refresh the entire name list.

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
  names = new Array<string>();

  name: string = '';

  ngOnInit() {
    this.Refresh();
  }

  remove(i: number) {
    this.names.splice(i, 1);
  }

  addMovie() {
    this.names.push(this.name);
    this.name = '';
  }

  Refresh() {
    console.log('refresh');
    this.names = ['Manish', 'Rahul', 'Ashish', 'Aditya', 'Rohan'];
  }
}

HTML

<p>App Component</p>
<ul>
    <li *ngFor="let name of names; index as i">
        {{i}}. {{name}} <button (click)="remove(i)">remove</button>
    </li>
</ul>

<button (click)="Refresh()">Refresh>/<button> <br/>

Name : <input type="text" [(ngModel)]="name">
<button (click)="addMovie()">Add Name</button>

Sunday, May 28, 2023

Angular- Directive to Allow Number Only in Input Textbox

Directive to Allow Number Only in Input Textbox

In this post, we will create a directive which will allow only numbers to input textbox. User will not allow to enter any other value, only numbers.

Below is the code of directive which will check the input value and allow if the input value is number-

import { Directive, HostListener } from '@angular/core';

@Directive({ selector: '[allowNumberOnly]' })
export class AllowNumberOnly {
  readonly NUMBER_REGEX = '^[0-9]';
  @HostListener('keypress', ['$event'])
  onKeyPress(event: any): boolean {
    if (!new RegExp(this.NUMBER_REGEX).test(event.key)) {
      return false;
    }
    return true;
  }
}

To use the directive in application, we need to add the directive under declarations array of App Module file.

^ Scroll to Top