From fee6dbf5264a30a80dfbe6b1babb7dc53215512d Mon Sep 17 00:00:00 2001 From: arturovt Date: Thu, 19 Nov 2026 20:47:34 +0200 Subject: [PATCH] fix(core): throw coded error when @for collection is not iterable Consider the following example: ```ts @Component({ template: '@for (item of items; track item) {{{ item }}}', }) class App { items = {0: 'a', 1: 'b'}; } ``` Prior to this commit, `reconcile()` treated every non-nullish value that is not an array as an iterable and called `Symbol.iterator` on it without a check. A plain object therefore failed with a raw `TypeError`: ``` TypeError: t[Symbol.iterator] is not a function ``` That error carries no code, does not mention `@for`, and does not say which template produced it. In a production build the stack is minified, so error reporting shows nothing actionable. The same value through `*ngFor` reports NG02200, which names the problem and suggests the keyvalue pipe, so `@for` was harder to debug than the API it replaces. With this commit the same value throws NG0957. Only the message text is behind `ngDevMode`; the check itself is not, because production is where the raw error is unreadable today. The array fast path is untouched, and `null` and `undefined` keep rendering nothing. The code is negative, which is how this package marks codes that have a guide on angular.dev, so the fix ships with one. --- adev/src/content/reference/errors/NG0957.md | 34 ++++++++ adev/src/content/reference/errors/overview.md | 1 + goldens/public-api/core/errors.api.md | 2 + packages/core/src/errors.ts | 1 + .../core/src/render3/list_reconciliation.ts | 15 +++- .../test/acceptance/control_flow_for_spec.ts | 77 +++++++++++++++++++ 6 files changed, 128 insertions(+), 2 deletions(-) create mode 100644 adev/src/content/reference/errors/NG0957.md diff --git a/adev/src/content/reference/errors/NG0957.md b/adev/src/content/reference/errors/NG0957.md new file mode 100644 index 00000000000..4fc03055260 --- /dev/null +++ b/adev/src/content/reference/errors/NG0957.md @@ -0,0 +1,34 @@ +# Collection used in @for is not iterable + +A `@for` loop repeats over an array, or over a value that implements the [iterable protocol](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols), such as a `Map`, a `Set` or a generator. This error means the collection was neither, most often a plain object: + +```angular-ts +@Component({ + template: `@for (item of items; track item) { + {{ item }} + }`, +}) +class Test { + items = {first: 'a', second: 'b'}; +} +``` + +`null` and `undefined` render nothing instead of throwing, so this error only reports a value that is present but cannot be iterated. + +## Fixing the error + +To repeat over the entries of a plain object, use the [KeyValue pipe](/api/common/KeyValuePipe): + +```angular-ts +@Component({ + imports: [KeyValuePipe], + template: `@for (item of items | keyvalue; track item.key) { + {{ item.key }}: {{ item.value }} + }`, +}) +class Test { + items = {first: 'a', second: 'b'}; +} +``` + +If the collection comes from an API call or another dynamic source, check that the value is the list itself. A response that wraps the list in another object, such as `{data: [...]}`, is a common cause. diff --git a/adev/src/content/reference/errors/overview.md b/adev/src/content/reference/errors/overview.md index e4f0cc2158a..8c4d44ed504 100644 --- a/adev/src/content/reference/errors/overview.md +++ b/adev/src/content/reference/errors/overview.md @@ -41,6 +41,7 @@ | `NG0951` | [Child query result is required but no value is available](errors/NG0951) | | `NG0955` | [Track expression resulted in duplicated keys for a given collection](errors/NG0955) | | `NG0956` | [Tracking expression caused re-creation of the DOM structure](errors/NG0956) | +| `NG0957` | [Collection used in @for is not iterable](errors/NG0957) | | `NG0991` | [Resource completed before producing a value](errors/NG0991) | | `NG01002` | [Missing Control Value](errors/NG01002) | | `NG01055` | [Missing control for `formControlName`](errors/NG01055) | diff --git a/goldens/public-api/core/errors.api.md b/goldens/public-api/core/errors.api.md index c2cfc8f3ce1..f3452f4f1f5 100644 --- a/goldens/public-api/core/errors.api.md +++ b/goldens/public-api/core/errors.api.md @@ -108,6 +108,8 @@ export const enum RuntimeErrorCode { // (undocumented) INVALID_STYLE_PROP_VALUE = -318, // (undocumented) + LOOP_INVALID_COLLECTION = -957, + // (undocumented) LOOP_TRACK_DUPLICATE_KEYS = -955, // (undocumented) LOOP_TRACK_RECREATE = -956, diff --git a/packages/core/src/errors.ts b/packages/core/src/errors.ts index a8eb0ee9796..9a79ee6d59a 100644 --- a/packages/core/src/errors.ts +++ b/packages/core/src/errors.ts @@ -152,6 +152,7 @@ export const enum RuntimeErrorCode { // Repeater errors LOOP_TRACK_DUPLICATE_KEYS = -955, LOOP_TRACK_RECREATE = -956, + LOOP_INVALID_COLLECTION = -957, // Runtime dependency tracker errors RUNTIME_DEPS_INVALID_IMPORTED_TYPE = 980, diff --git a/packages/core/src/render3/list_reconciliation.ts b/packages/core/src/render3/list_reconciliation.ts index 41c54b7c97b..150b14bcd2e 100644 --- a/packages/core/src/render3/list_reconciliation.ts +++ b/packages/core/src/render3/list_reconciliation.ts @@ -8,7 +8,7 @@ import {setActiveConsumer, type ReactiveNode} from '@angular/core/primitives/signals'; import {TrackByFunction} from '../change_detection'; -import {formatRuntimeError, RuntimeErrorCode} from '../errors'; +import {formatRuntimeError, RuntimeError, RuntimeErrorCode} from '../errors'; import {stringifyForError} from './util/stringify_utils'; @@ -243,8 +243,19 @@ export function reconcile( } else if (newCollection != null) { // iterable - immediately fallback to the slow path setActiveConsumer(reactiveConsumer); - const newCollectionIterator = newCollection[Symbol.iterator](); + const iteratorFn = newCollection[Symbol.iterator]; + const newCollectionIterator = + typeof iteratorFn === 'function' ? iteratorFn.call(newCollection) : null; setActiveConsumer(null); + + if (newCollectionIterator === null) { + throw new RuntimeError( + RuntimeErrorCode.LOOP_INVALID_COLLECTION, + ngDevMode && + `@for expected an array or an iterable, but got ${typeof newCollection}. ` + + `Did you mean to use the keyvalue pipe?`, + ); + } let newIterationResult = newCollectionIterator.next(); while (!newIterationResult.done && liveStartIdx <= liveEndIdx) { const liveValue = liveCollection.at(liveStartIdx); diff --git a/packages/core/test/acceptance/control_flow_for_spec.ts b/packages/core/test/acceptance/control_flow_for_spec.ts index 8e6a07d0a25..d883f1f7af8 100644 --- a/packages/core/test/acceptance/control_flow_for_spec.ts +++ b/packages/core/test/acceptance/control_flow_for_spec.ts @@ -22,6 +22,7 @@ import { TemplateRef, ViewContainerRef, } from '../../src/core'; +import {global} from '../../src/util/global'; import {TestBed} from '../../testing'; describe('control flow - for', () => { @@ -196,6 +197,82 @@ describe('control flow - for', () => { expect(fixture.nativeElement.textContent).toBe('1(0/0)|3(1/1)|'); }); + describe('invalid collections', () => { + const _global: {ngDevMode: any} = global; + let saveNgDevMode!: typeof ngDevMode; + beforeEach(() => (saveNgDevMode = ngDevMode)); + afterEach(() => (_global.ngDevMode = saveNgDevMode)); + + function createFixture(initial: unknown) { + @Component({ + template: '@for (item of items(); track $index) {{{item}}|}', + }) + class TestComponent { + items = signal(initial); + } + + return TestBed.createComponent(TestComponent); + } + + it('should throw a coded error when the collection is a plain object', async () => { + const fixture = createFixture({0: 'a'}); + + await expectAsync(fixture.whenStable()).toBeRejectedWithError( + /NG0957: @for expected an array or an iterable, but got object/, + ); + }); + + it('should throw a coded error when a valid collection is replaced by a plain object', async () => { + const fixture = createFixture(['a', 'b']); + await fixture.whenStable(); + expect(fixture.nativeElement.textContent).toBe('a|b|'); + + fixture.componentInstance.items.set({0: 'a'}); + + await expectAsync(fixture.whenStable()).toBeRejectedWithError(/NG0957/); + }); + + it('should render a Set', async () => { + const fixture = createFixture(new Set(['a', 'b'])); + await fixture.whenStable(); + expect(fixture.nativeElement.textContent).toBe('a|b|'); + }); + + it('should render a Map', async () => { + const fixture = createFixture(new Map([['a', 1]])); + await fixture.whenStable(); + expect(fixture.nativeElement.textContent).toBe('a,1|'); + }); + + it('should render a custom iterable', async () => { + const iterable = { + *[Symbol.iterator]() { + yield 'a'; + yield 'b'; + }, + }; + const fixture = createFixture(iterable); + await fixture.whenStable(); + expect(fixture.nativeElement.textContent).toBe('a|b|'); + }); + + it('should render a string as its characters', async () => { + const fixture = createFixture('ab'); + await fixture.whenStable(); + expect(fixture.nativeElement.textContent).toBe('a|b|'); + }); + + it('should render nothing for null and undefined', async () => { + const fixture = createFixture(null); + await fixture.whenStable(); + expect(fixture.nativeElement.textContent).toBe(''); + + fixture.componentInstance.items.set(undefined); + await fixture.whenStable(); + expect(fixture.nativeElement.textContent).toBe(''); + }); + }); + describe('trackBy', () => { it('should have access to the host context in the track function', async () => { let offsetReads = 0;