Implementing Control Flow Syntax for Cleaner Angular Templates
Guidelines for using new control flow syntax to simplify and enhance the readability of Angular templates.
0 likes
7 views
Rule Content
{ "title": "Implementing Control Flow Syntax for Cleaner Angular Templates", "description": "Guidelines for using new control flow syntax to simplify and enhance the readability of Angular templates.", "category": "Angular Cursor Rules", "rules": [ { "id": "prefer-control-flow-syntax", "description": "Use the new control flow syntax (`@if`, `@for`, `@switch`) instead of the older directives (`*ngIf`, `*ngFor`, `*ngSwitch`) to improve template readability and maintainability.", "severity": "error", "examples": { "bad": [ { "code": "<div *ngIf=\"isLoggedIn\">Welcome back!</div>" }, { "code": "<ul><li *ngFor=\"let item of items\">{{ item.name }}</li></ul>" }, { "code": "<div [ngSwitch]=\"status\"><p *ngSwitchCase=\"'active'\">Active</p><p *ngSwitchDefault>Inactive</p></div>" } ], "good": [ { "code": "@if (isLoggedIn) { <div>Welcome back!</div> }" }, { "code": "<ul>@for (item of items; track item.id) { <li>{{ item.name }}</li> }</ul>" }, { "code": "@switch (status) { @case ('active') { <p>Active</p> } @default { <p>Inactive</p> } }" } ] } }, { "id": "require-track-in-for", "description": "Always include a `track` expression in `@for` loops to optimize rendering performance by uniquely identifying each item.", "severity": "error", "examples": { "bad": [ { "code": "@for (item of items) { <li>{{ item.name }}</li> }" } ], "good": [ { "code": "@for (item of items; track item.id) { <li>{{ item.name }}</li> }" } ] } }, { "id": "use-empty-in-for", "description": "Utilize the `@empty` block in `@for` loops to handle cases where the iterable is empty, providing a fallback UI.", "severity": "warning", "examples": { "bad": [ { "code": "@for (item of items; track item.id) { <li>{{ item.name }}</li> }" } ], "good": [ { "code": "@for (item of items; track item.id) { <li>{{ item.name }}</li> } @empty { <li>No items available.</li> }" } ] } }, { "id": "prefer-switch-over-multiple-ifs", "description": "Use `@switch` statements instead of multiple `@if` statements when evaluating the same expression against multiple values to enhance code clarity.", "severity": "warning", "examples": { "bad": [ { "code": "@if (status === 'active') { <p>Active</p> } @else if (status === 'inactive') { <p>Inactive</p> } @else { <p>Unknown status</p> }" } ], "good": [ { "code": "@switch (status) { @case ('active') { <p>Active</p> } @case ('inactive') { <p>Inactive</p> } @default { <p>Unknown status</p> } }" } ] } } ] }