Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a boolean template variable in angular 2?

I want to show or hide a section by click of a button. I don't want to create a variable in the controller. Is there a way to do this by using local template variables (using #variableName)?

I am thinking something like below. But for this I am getting template parse error.

  <button color="primary" #showSection1="true" (click)="!showSection1;">Toggle</button>
  <p *ngIf="showSection1">
    This should be shown or hidden on click of the button.
  </p>
like image 393
Koushik Sarkar Avatar asked Jan 18 '17 19:01

Koushik Sarkar


1 Answers

You can't do it that way because template variable stores entire button element when you declare it like that, but you can take advantage of ternary operator here:

<button (click)="showSection1 ? showSection1 = false : showSection1 = true;">Toggle</button>
<p *ngIf="showSection1">
    This should be shown or hidden on click of the button.
</p>

When showSection1 is undefined or has false value, it will be set to true and vice versa.

Here's working Plunker.

like image 125
Stefan Svrkota Avatar answered Oct 03 '22 08:10

Stefan Svrkota