Common Angular Performance Mistakes

In this tutorial, you will learn common Angular Performance mistakes and how to fix them. There are many common Angular Performance mistakes.

1. Using Default Change Detection

By default, Angular uses the Default change detection strategy.

The default change detection strategy means Angular checks components on every change detection cycle.

Example:


@Component({
selector: 'myapp-example',
})

You should use OnPush Change Detection

Example:


@Component({
selector: 'myapp-example',
changeDetection: ChangeDetectionStrategy.OnPush
})

2. Mutating (New form) of Objects and Arrays

Angular relies on reference changes.

Mistakes


// suppose you are adding name into user Object
this.user.name = 'John'; // Object example
// suppose you are adding newItem into items array
this.items.push(newItem); // array example

Correct way


// suppose you are adding name into user Object
this.user = { ...this.user, name: 'John' };
// suppose you are adding newItem into items array
this.items = [...this.items, newItem];

3. Implement Heavy Logic Inside Templates

You should not implement heavy logic inside the template file.

Mistakes


<p>{{ MultiplyEvenNumbers() }}</p>

Correct way

You have to implement logic in the component ts file.


calculate = this.MultiplyEvenNumbers();

4. Not Using trackBy in *ngFor

If you are not using trackBy in *ngFor, then Angular recreates DOM elements unnecessarily.

Mistakes


<div *ngFor="let item of items">{{ item.name }}</div>

Correct way


<div *ngFor="let item of items">{{ item.name }}</div>

// component.ts file
trackById(index: number, item: any) {
return item.id;
}

5. Too Many Subscriptions (Memory Leaks)

If you are using manually subscribing without unsubscribing then the causes of performance and memory issues.

Mistake


this.data$.subscribe(data => this.data = data);

Correct way


<p>{{ data$ | async }}</p>

Note: When we use | async then it will be automatic unsubscribe.

6. Loading Everything at Once (No Lazy Loading)

When you use loading everything at once then large bundles will slow down in initial load time.

Solutions

You can create modules according your requirement.


{
path: 'admin',
loadChildren: () => import('./admin/admin.module').then(m => m.AdminModule)
}

Common Angular Performance Mistakes – Interview Questions

Q 1: Why is excessive change detection harmful?

Ans: It increases CPU usage and reduces application performance.

Q 2: What happens if large data is bound directly in templates?

Ans: It slows rendering and affects performance.

Q 3: Why avoid unnecessary subscriptions?

Ans: They can cause memory leaks and degrade performance.

Q 4: Why is lazy loading important?

Ans: It reduces initial loading time.

Q 5: Why should trackBy be used in ngFor?

Ans: It improves rendering performance by tracking item identity.