Angular Optimization: OnPush

· 171 words · 1 minute read

Angular’s default change detection strategy: reliable but sometimes overkill. Enter the OnPush Strategy.

Angular, by default, uses a comprehensive approach for change detection. It checks every component for updates on various triggers - HTTP responses, user interactions, and so on. However, this thoroughness can come at the cost of performance.

When dealing with heavy, intricate components that demand significant computing resources, optimizing change detection strategy can make a difference. One effective way to achieve this is by switching to the OnPush strategy.

Here’s a simple example:

@Component({
  selector: "app-my-component",
  template: ` <div>{{ myInput }}</div> `,
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class MyComponent {
  @Input() myInput: string;
}

By making this change, our component will now update only when the myInput property changes, potentially improving the efficiency of our app.

Remember, this isn’t a silver bullet for all performance issues. If your input data frequently changes, this change may not significantly impact performance. As with all optimization techniques, it’s essential to consider the specific needs and characteristics of your application before making changes.