Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change ng-template variable in Angular 5

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?

like image 214
mtonev Avatar asked Feb 03 '26 06:02

mtonev


1 Answers

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.

like image 118
Reactgular Avatar answered Feb 05 '26 23:02

Reactgular



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!