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.
@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);
}
Simply add the appLifecycleLogger directive to any element you want to track:
<div appLifecycleLogger>This element will be tracked</div>Open your browser's console and click the buttons below to see the lifecycle events: