I'm using the following code to iterate a bunch of custom controls. Since those need to know some stuff, like index and position in the structure, I'm passing in a config object to keep the junk together like this.
<div *ngFor="let thing of stuff; let first=first; let last=last; let index = index;">
<app-thingy [data]="thing"
[config]="{first:first,last:last,index:index}">
</app-thingy>
</div>
I'd prefer to keep the code more compact and it seems like a very repetitive syntax with let
this and let
that. So I figured that I could create the object straight off in the iterative tag like this.
<div *ngFor="let thing of stuff; let config={first:first,last:last,index:index};">
<app-thingy [data]="thing"
[config]="config">
</app-thingy>
</div>
However, Angular barks at this claiming that the curly bracket in the definition of config
is an invalid syntax.
Uncaught Error: Template parse errors:
Parser Error: Unexpected token {, expected identifier, keyword, or string at column 45 in [let thing of stuff; let config={first:first,last:last,index:index};] in
...
<div [ERROR ->]*ngFor="let thing of stuff; let config=
As far I can goolearch it, the syntax is wrong but I can't see why. Can someone, please, shed some light on why those two samples aren't equivalent?
I noticed that using new MyType(...)
in the HTML markup isn't working neither but that's apparently by design. However, this is a anonymous object (type any
) so I'm a bit puzzled.
You cannot declare an object using let inside the component.html
WRONG
<div *ngFor="let thing of stuff; let config={first:first,last:last,index:index};">
Instead you can create the object in ts and pass it in the HTML
This is wrong
<div *ngFor="let thing of stuff; let config={first:first,last:last,index:index};">
<app-thingy [data]="thing"
[config]="config">
</app-thingy>
</div>
Because first:first,last:last,index:index referencing to loop condition, they are not handled as objects. You can understand it as for loop in javascript like
for(let i=0; i<somelength ;i++){}
like i=0
is equal to first:first
and somelength equals last:last
and i as index:index
. They can't be passed like above.
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.