mirror of
https://github.com/angular/angular.git
synced 2026-11-22 22:55:25 -05:00
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.
(cherry picked from commit fee6dbf526)
This commit is contained in:
@@ -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.
|
||||
@@ -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) |
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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<T, V>(
|
||||
} 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);
|
||||
|
||||
@@ -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<any>(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;
|
||||
|
||||
Reference in New Issue
Block a user