li x
li x

Reputation: 4051

How to instantiate and use subsequent array inside ngFor?

*ngFor="let arr = ['foo', 'bar', 'sla']; let item of arr; let i = index;"

Why when providing that the instantiation of arr before let item of arr; does this raise an exception of [object Object] or rather why can't I do this?

The reason I don't want to do let item of [...] is because then I would also have to put this information into my .ts file which I don't want to do.

I want to have the ability to go back and reference this array from inside my html so I need a way of refferencing the declared array without instantiating it in the data file.

stack trace for reference:

ERROR 
Error: [object Object]
Stack trace:
resolvePromise@webpack-internal:///./node_modules/zone.js/dist/zone.js:795:31
resolvePromise@webpack-internal:///./node_modules/zone.js/dist/zone.js:766:17
scheduleResolveOrReject/<@webpack-internal:///./node_modules/zone.js/dist/zone.js:844:17
ZoneDelegate.prototype.invokeTask@webpack-internal:///./node_modules/zone.js/dist/zone.js:425:17
onInvokeTask@webpack-internal:///./node_modules/@angular/core/esm5/core.js:4956:24
ZoneDelegate.prototype.invokeTask@webpack-internal:///./node_modules/zone.js/dist/zone.js:424:17
Zone.prototype.runTask@webpack-internal:///./node_modules/zone.js/dist/zone.js:192:28
drainMicroTaskQueue@webpack-internal:///./node_modules/zone.js/dist/zone.js:602:25

Upvotes: 1

Views: 99

Answers (1)

Sanoj_V
Sanoj_V

Reputation: 2986

You need to instantiate you array as would would normally but afterwards you need to add as which will allow you to make a reference to the array in html:

*ngFor="let item of ['foo', 'bar', 'sla'] as arr; let i = index;"

Afterwards you can then just say {{arr.length}} as expected.

Upvotes: 5

Related Questions