Reputation: 971
I have an object some like this:
this.obj = {{name: 'Hello 1'}, {'name': 'Hello 2'}}
I'm making a loop through this object on angular 2 (ionic2):
<div class"item" *ngFor="let item as obj">
<span>{{item.name}}</span>
<span>{{item.count}}</span>
</div>
item.count
doesn't exists, and, obviously, It will not be rendered in the view. But I need to instanciate this property in the view. In angular 1 I think something like ng-init="item.count = 0"
should solve this issue, but It's not enabled in Angular 2.
Upvotes: 3
Views: 2372
Reputation: 8335
UPDATE PER COMMENTS
The solution appears to be a bug in Angular itself, as Aluan noted using dot property assignment results in "Bindings cannot contain assignments at column 41" so I have opened a github issue
ORIGINAL
If you want to do it in the template then you can dynamically add a property in JS (which TypeScript is a superset of, and therefore this is technically valid) via the object['propertyName']
syntax.
The HTML for the template becomes
<div class="item" *ngFor="let item of obj">
<span>{{item.name}}</span>
<span>{{item['count'] ? item['count'] : item['count'] = 0}}</span>
<button (click)="increment(item)">plus</button>
<button (click)="decrement(item)">minus</button>
</div>
And the code for the button logic:
increment(item) {
item.count++;
}
decrement(item) {
item.count--;
}
Working example: http://plnkr.co/edit/b5fe87kFm2nxs3kabZRo?p=preview
Upvotes: 1