简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM