feat(eslint-plugin-template): add rule prefer-at-empty #2352
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Closes #2350
New rule
@angular-eslint/template/prefer-at-empty
will find code in templates where the@empty
block of a@for
block could be used instead of using an@if
block.For example, it will find this:
and change it to this:
I originally wrote this to just report the problems and not provide a fix, however because there are a few different scenarios that it detects, it wasn't always obvious how to fix the problem. I considered using the message to explain what needs to change, but then I figured if it's going to explain what needs to be changed, why not just change it!
The fixes change the code enough to make the problem go away, but it doesn't do any formatting, so the expected output in the tests can look a bit messy, but a formatter like Prettier will fix that up nicely.
There are six different scenarios that can be detected. Of course, in each scenario, the collection used in the
for
block must be the same collection used in the@if
blocks. The scenarios are:@for
followed by an "is empty"@if
:@if
followed by@for
:@if
with an@else
, where the@if
branch contains a@for
:@if (items.length > 0) { @for (item of items; track $index) { } } @else { }
@if
with an@else
, where the@else
branch contains a@for
:@if
with a@for
, followed by an "is empty"@if
:@if (items.length > 0) { @for (item of items; track $index) { } } @if (items.length === 0) { }
@if
followed by an "is not empty"@if
with a@for
:@if (items.length === 0) { } @if (items.length > 0) { @for (item of items; track $index) { } }