Rule Proposal: Prefer contextual variables in control flow @for
blocks
#2203
Closed
reduckted
started this conversation in
New Rule Proposals
Replies: 2 comments
-
I have an implementation of this rule here: https://github.com/reduckted/angular-eslint/tree/feature/prefer-contextual-for-variables |
Beta Was this translation helpful? Give feedback.
0 replies
-
Implemented in #2311. |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
The Problem
When using the
*ngFor
directive, you could access certain exported values likeindex
,first
andlast
. For example:When using the
@for
control flow statement, those variables can now be accessed within the block without aliasing them.Those variables can also be aliased, however that is often not required. For example, aliasing
$index
in this example is unnecessary.When migrating from
*ngFor
to control flow syntax, the Angular migration keeps the aliasing, so you can end up with unnecessary aliases.Rule Proposal
A lint rule that finds unnecessary aliases would assist with cleaning up the migration as well as guiding developers who are unfamiliar with the ability to use the contextual variables.
The rule should report any contextual variables in
@for
statements that are aliased. An option can be provided for each contextual variable to allow specific aliases to be allowed. For example,{ allowedAliases: { $index: ['i'] }
would allowi
to be used as an alias for$index
.Nested Blocks
There are legitimate use cases for aliasing these variables. For example, with nested
@for
blocks, you may need to know the index from the outer block within the inner block, so using the implicit$index
variable would not be suitable. When there are nested@for
blocks, aliasing should be allowed.Simplification
There are some cases where an expression using a contextual variable can be simplified. For example,
$index === 0
can be simplified to$first
. Similar simplifications can be used for$last
,$even
and$odd
. This would be useful for developers who may be aware of$index
but not aware of the other contextual variables that can be used (plus it simplifies the templates).References
Beta Was this translation helpful? Give feedback.
All reactions