angular: Problem with ngFor
With this pattern:
`<li *ngFor=“let test of testItems; let i = index”> <input type=“text” [(ngModel)]=“test” />
`I got this error: Cannot assign to a reference or variable! Last call on stack before exception: at _AstToIrVisitor.visitPropertyWrite (http://localhost:5001/node_modules/@angular/compiler/src/view_compiler/expression_converter.js
testItems is an array of string. If it was an array oj object and i put for instance test.Text into [(ngModel)] all is ok. It’s more than 6 months I use Angular2 by now but I couldn’t understand this issue…
About this issue
- Original URL
- State: closed
- Created 8 years ago
- Reactions: 3
- Comments: 17 (5 by maintainers)
Wouldn’t
[(ngModel)]="testItems[i]"
do the trick?I think that the error is saying that you can assign input’s value to a dynamically created variable (and
test
is a dynamically created local var)let foo
creates a local variable andngModel
can’t assign to local variables. You can only assign to properties (fields) of your component.@meiriko You need to add
trackBy
tongFor
It is related to this, #4402I tried this approach yet the input field looses focus after the first letter I enter. Any ideas?
@meiriko GitHub issues are for bug reports and feature requests. For support questions please use other channels like the ones listed in CONTRIBUTING - Got a Question or Problem?
@sirhcybe you forgot to put your trackBy function to the template. Your
*ngFor
on the template should havetrackBy:customTrackBy
instead.Here, it’s fixed https://plnkr.co/edit/tLdmWGL22ZluIdJmTUpO?p=preview
For those who have an issue with the inputs (focus lost when you type a single letter) and ended up there, the answer provided by @harunurhan works like a charm.
Hi @pamerio,
There is nothing wrong in the pattern. Issue is in the index declaration i.e. reference doesn’t work if you declare the index separately.
`<li *ngFor=“let test of testItems; let i = index”> <input type=“text” [(ngModel)]=“test” />
Your pattern will work, if you take out the “let i = index” without this template treat this as an object. and you will not have any option to manipulate the index, like delete.
If you still need to use index, then best option if to refer direct object of the array like
<input type=“text” [(ngModel)]=“testItems[i]” />
Hope this clarifies.
Thanks,