Still typing *ngFor, *ngIf, and *ngSwitch
out of habit? Youāre not alone. After years of working with legacy Angular, my muscle memory made it hard to switch to the latest Angular control flow syntax. But with one simple trick, I finally made the shiftāand it improved both my code and performance. In this post, Iāll show you how to ditch the old directives and get comfortable with Angularās new control flow in no time
The Simple Trick? Let ESLint Do the Work for You
Instead of forcing myself to remember, I let ESLint catch me in the act.
Angular now supports ESLint rules that can warn or error when you use legacy structural directives like *ngFor, *ngIf, and *ngSwitch
and instead suggest using the new control flow syntax @for, @if, @switch
.
After Eslint Rule:
After adding the rule code editor highligts the error
Solution: Add This ESLint Rule to Your Project
To make the switch easier, you can add the following rule to your eslint.config.js under the html rules section:
{
files: ["**/*.html"],
extends: [
...angular.configs.templateRecommended,
...angular.configs.templateAccessibility,
],
rules: {
"@angular-eslint/template/prefer-control-flow": "error"
},
}
"@angular-eslint/template/prefer-control-flow": "error"
Once you add this rule, run ng lint to catch any instances of the old directives:
12:37 error Use built-in control flow instead of directive ngIf @angular-eslint/template/prefer-control-flow
16:15 error Use built-in control flow instead of directive ngIf @angular-eslint/template/prefer-control-flow
Benefits of Using the New Syntax
Switching to Angularās new control flow syntax isnāt just about cleaner codeāitās also about performance improvements. The new directives are optimized to work faster, which can make a noticeable difference in larger applications.
Final Thoughts
Switching from *ngIf, *ngFor, and *ngSwitch to Angularās new control flow syntax can be a tough habit to breakābut with the right ESLint rules in place, the transition becomes effortless. Youāll write cleaner, more performant code without having to constantly remind yourself to use the new syntax.
Want to take it a step further? Combine this lint rule with a commit-stage linting setup to automatically prevent legacy control flow usage from making it into your codebase. In this related guide, I walk you through how to do exactly that:
š Maintain Code Quality Like a Big Tech Team Without Paying for Expensive Automation
By combining ESLint rules with pre-commit hooks, you ensure that your team consistently follows the latest Angular best practicesāwith zero manual effort.
š¼ļø Banner generated using OpenAI Sora
Top comments (1)
Honestly, changing old habits like this feels rough but I'm down with anything that keeps my code clean and quick.