Reputation: 325
When I try to change a ng-template variable on click inside the template I receive an error(Uncaught Error: Cannot assign to a reference or variable!)
<ng-template let-o="opened" [ngTemplateOutletContext]="{ opened: d === 0 }" [ngTemplateOutlet]="item" #item>
<div class="columns table-header is-marginless">
<button (click)="o = !o">+</button>
<div [hidden]="!o">Toggle me on button click</div>
</div>
</ng-template>
So how to access the local 'o' variable in order change it?
Upvotes: 3
Views: 1752
Reputation: 54771
When Angular renders a template it creates a new context each time, and uses that context to render the HTML. That means, that any changes made later to that context are thrown away when the template is rendered again. Therefore, every time the template is rendered the value of o
is always d === 0
.
The error message Cannot assign to a reference or variable
is just there to stop you from trying to modify those temporary values. Since any changes will be lost the next time the template renders.
The (click)
event should be mutating the value of d
instead. So that when the next context is created the value of o
represents the new state.
Upvotes: 1