← 输入框|github.com|刷新
Skip to content

@for(ID of IDs; track ID) and NG0956 - provide a way to prevent warning when tracking by item is legit scenario #56471

Open

Description

@montella1507

Which @angular/* package(s) are the source of the bug?

core

Is this a regression?

Yes

Description

We are rendering nodes:

@for(id of ids; track id) {
 <node [id]="id"/>
}
image

But we are getting NG0956 warning:
...and make sure that it uniquely identifies items in a collection

I understood is it usually not good idea to track collection nodes by themselves.

However, this is exception, because collection is list of IDs of the nodes and "ID" is unique identifier of the node.

Please reconsider the warning. I think the framework should have not thrown this warning if the element of the collection may be unique key (maybe it should throw this warning only when "id" is object and not string / number)

Please provide a link to a minimal reproduction of the bug

No response

Please provide the exception or error you saw

NG0956: The configured tracking expression (track by identity) caused re-creation of the entire collection of size 1. This is an expensive operation requiring destruction and subsequent creation of DOM nodes, directives, components etc. Please review the "track expression" and make sure that it uniquely identifies items in a collection. Find more at https://angular.io/errors/NG0956

Please provide the environment you discovered this bug in (run ng version)

Angular CLI: 18.0.1
Node: 20.9.0
Package Manager: yarn 1.22.19
OS: darwin arm64

Angular: 18.0.0
... animations, cdk, common, compiler, compiler-cli, core, forms
... language-service, localize, platform-browser
... platform-browser-dynamic, router, service-worker

Package                         Version
---------------------------------------------------------
@angular-devkit/architect       0.1800.1
@angular-devkit/build-angular   18.0.1
@angular-devkit/core            18.0.1
@angular-devkit/schematics      18.0.1
@angular/cli                    18.0.1
@schematics/angular             18.0.1
ng-packagr                      18.0.0
rxjs                            7.8.1
typescript                      5.4.5
webpack                         5.89.0
zone.js                         0.14.6

Anything else?

...or just provide a way how to halt / mute this warning.

Activity

  1. changed the title [-]@for(ID of IDs; track ID) and NG0956[/-] [+]@for(ID of IDs; track ID) and NG0956 - do not show warning when collection is tracked by collection items of primitive type[/+] on Jun 16, 2024
  2. changed the title [-]@for(ID of IDs; track ID) and NG0956 - do not show warning when collection is tracked by collection items of primitive type[/-] [+]@for(ID of IDs; track ID) and NG0956 - provide a way to prevent warning when tracking by item is legit scenario[/+] on Jun 16, 2024
  3. JeanMeche commented on Jun 17, 2024

    @JeanMeche
    Member

    Hi, could try to produce a narrowed down repro ?
    What is the type of id ?

  4. montella1507 commented on Jun 17, 2024

    @montella1507
    Author

    https://stackblitz.com/edit/stackblitz-starters-1qz55n?file=src%2Fmain.ts

    Here.

    schema().children is computed signal. ID is of type string.

    image

    Signal store is not needed to simulate this warning. However, maybe computed/signals are.

  5. JeanMeche commented on Jun 17, 2024

    @JeanMeche
    Member

    I can be narrowed down to this : Updating the array by keeping the same size but replacing all values.

    @Component({
      selector: 'app-root',
      standalone: true,
      template: `
        @for (id of schema; track id) {
           <span>{{id}}</span>
        }
    
         <button (click)="foo()">Click me!</button>
      `,
    })
    export class App {
      schema = ['1', '2', '3'];
      foo() {
        this.schema = ['5', '6', '7'];
      }
    }
    
  6. added
    area: core
    core: control flow
    on Jun 17, 2024
  7. modified the milestone: needsTriage on Jun 17, 2024
  8. pkozlowski-opensource commented on Jun 20, 2024

    @pkozlowski-opensource
    Member

    We are still trying to decide on the best API for opting out of this warning for the legitimate cases where a given collection needs to be re-created. For now a work-around is to create an identity method on a component: https://stackblitz.com/edit/stackblitz-starters-ytmizy?file=src%2Fmain.ts

    This is not the most ergonomic way, but this is what we've got right now.

  9. montella1507 commented on Aug 30, 2024

    @montella1507
    Author

    Hello, any news?

  10. Socratezz commented on Sep 30, 2024

    @Socratezz

    Another vote for this a month later. Any updates?

  11. andersb commented on Oct 22, 2024

    @andersb

    Just ran into this issue.

    In my case, I have a TableComponent which is used to display any kind of Array throughout the application. And there are hundreds of places where this is used.
    In almost all cases, I will fetch data from backend and the result will be saved to a property in the page-component which is then used to send into the TableComponent through @input rows: Array

    For example. in CustomersComponent, this is stripped down to what is fetched from backend.

    this.customerService.getCustomers(searchQuery).subscribe({
      next: (pagedList: PagedListDto<CustomerDto>) => {
        this.customers = pagedList.items;
      }
    });
    

    Every time I will do any kind of action that will trigger CustomerComponent to fetch data from server, the warning about recreating is shown.
    This is where I don't really see why I get the warning. I want the table to recreate all the rows because I got a new collection from backend.

    So, to avoid the warning, I see 2 different solutions.

    First one is to provide my TableComponent with information what property of a row-object is to be considered unique.
    In my example of Customers, the unique property would be customerNumber.
    The down side is that I would need to go through hundreds of places and explicitly say "this is the unique field".

    The second option, generate a unique value of the row-object.

    trackRowsBy(row: any): string {
      return Object.keys(row).map((key: string) => row[key]).join('-');
    }
    

    which is then used

    @for (row of rows; track trackRowsBy(row); let i = $index) {

    The question here would be, how much of a performance impact would the second option result in.
    I have a pretty strict pagination strategy so I will seldom show more than 50 rows at the same time.
    However, would it be considered bad design to generate a unique id of the data in regards to performance?

  12. zijianhuang commented on Oct 27, 2024

    @zijianhuang

    Yes, I have legitimate cases too:

    @for (idof data.annotationIds; track id) {
    <mat-chip (click)="showAnnotation(id)"><span
    		[ngClass]="getAnnotationChipColorById(id)">{{getAnnotationName(id)}}</span></mat-chip>
    }

    And the lookup by id is through a local dictionary.

    According to https://angular.dev/errors/NG0956, the rule is focused on the nominated scenario with the todo list.

    In my scenario, an article (data) is associated with many annotations which are shared by article objects.

  13. c-harding commented on Nov 19, 2024

    @c-harding

    @pkozlowski-opensource I found an even more light-weight workaround, when working with strings: append the empty string.

        @for (string of strings(); track string + '') {
  14. mihli-hf commented on Dec 23, 2024

    @mihli-hf

    Any update on this issue ?

  15. JeanRemiDelteil commented on Jan 29, 2025

    @JeanRemiDelteil

    Another case where the detection may be too sensitive:

    NG0956: The configured tracking expression (track by identity) caused re-creation of the entire collection of size 1. This is an expensive operation requiring destruction and subsequent creation of DOM nodes, directives, components etc. Please review the "track expression" and make sure that it uniquely identifies items in a collection. Find more at https://angular.dev/errors/NG0956

    entire collection of size 1 If the collection changes and is of size 1, yes, indeed that will be the entire collection.
    Also there are cases where we want to change the entire collection (when paginating display mostly, it makes sense to recreate the dom to avoid weird user state being kept).

  16. kshetline commented on Mar 11, 2025

    @kshetline

    My problem with this error message, apart from seeing too many of them, is I have no idea where the error is coming from. ɵɵrepeater | @ | core.mjs:27348 tells me nothing about where in my own code I should be trying to hunt down the issue. Please include the HTML file and line number, if possible, or at least a little more detail like the track-by identifier.

  17. JoostK commented on Mar 12, 2025

    @JoostK
    Member

    My problem with this error message, apart from seeing too many of them, is I have no idea where the error is coming from. ɵɵrepeater | @ | core.mjs:27348 tells me nothing about where in my own code I should be trying to hunt down the issue. Please include the HTML file and line number, if possible, or at least a little more detail like the track-by identifier.

    Expand the stack trace in the console to see which template the error originates.

  18. kshetline commented on Mar 13, 2025

    @kshetline

    Expand the stack trace in the console to see which template the error originates.

    I've done that, and there's nothing useful in the stack trace. Just references to Angular internals, nothing referencing my own code or my own templates.

  19. zyv commented on Apr 8, 2025

    @zyv

    My use case is this: An item is a message generated by the protobuf compiler. It doesn't have a unique id that I could use to identify it. I use identification by identity because that's the way it's supposed to be.

    https://github.com/rdamazio/efis-editor/blob/355803d3be1f8c093fea6cec4d8c8dd9ca3feb34/src/app/checklists/items-list/items-list.component.html#L14

    My understanding is that I should create a protected method that just returns the item to opt-out, but it doesn't look too nice. I would appreciate a better way.

  20. egonknapen commented on May 31, 2025

    @egonknapen

    And not only that completely ridiculous to throw hundreds of that same warning every time. Without any information about it. Lets assume you got a component and use it 10 times, got a @for in it, with 100 items, well your devtools crashes every time, because of the overflow.

  21. m-thompson-code commented on Aug 21, 2025

    @m-thompson-code

    @pkozlowski-opensource I found an even more light-weight workaround, when working with strings: append the empty string.

    @for (string of strings(); track string + '') {
    

    its upsetting that this is kind of the cleaning way of dealing with this issue for string arrays. :( can this issue be fixed soon? Seems silly

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

area: corecore: control flow

Type

No type

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions