Introduction: Component Lifecycle Logger

Understanding Component Lifecycle

Before we dive into performance issues, let's understand how we can track when Angular components are created and destroyed. We'll use a custom directive that logs these lifecycle events.

Lifecycle Logger Directive:


@Directive({
  selector: '[appLifecycleLogger]',
  standalone: true
})
export class LifecycleLoggerDirective implements OnInit, OnDestroy {
  private instanceId = Math.random().toString(36).substring(7);

  ngOnInit() {
    console.log('(+) Component created - Instance ID: ' + this.instanceId);
  }

  ngOnDestroy() {
    console.log('(-) Component destroyed - Instance ID: ' + this.instanceId);
}
          

How to Use It

Simply add the appLifecycleLogger directive to any element you want to track:

<div appLifecycleLogger>This element will be tracked</div>

Live Demo

Open your browser's console and click the buttons below to see the lifecycle events:

What's Next?

In the following steps, we'll use this directive to demonstrate how Angular handles component creation and destruction in different scenarios, particularly with *ngFor and performance optimizations.

Continue to NgFor Performance Issue →