简体   繁体   中英

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>

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 .

If you want to do this in a way that will work with AOT (Production) compilation, I would recommend using a template reference variable. For my example, I want to have the class open applied to my element when it is closed, and removed when it is clicked again. Basically, I want to toggle the open class on my element. Storing this state data in my component.ts file is ugly in my opinion.

To achieve this I do the following.

<li class="tagTag" *ngFor="let tag of tagCategory.tags" [ngClass]="{'open': toggle.value}" #toggle [value]="false" (click)="toggle.value = !toggle.value">...</li>

the #toggle stores the <li> instance as a Template Reference Variable called 'toggle'. I then use the value directive and give it a value of false . Using the click handler, I set the value of the value directive between true and false. My [ngClass] adds or removes the open class based upon the current value of the value directive on this template reference. This works with ahead-of-time compilation and allows you to keep superfluous variables out of your component. Use this with care though because, almost as a rule, you do not want to define variables in a template.

you may use below,

@Component({
  selector: 'my-app',
  template: `<h1>Hello {{name}}</h1>
   <label>
        <input type="checkbox" [(ngModel)]="showSection1" >
        Is Shown
    </label>
    <p *ngIf="showSection1">
      This should be shown or hidden on click of the button.
    </p>
  `
})
export class AppComponent { name = 'Angular'; }

Here is Plunker !!

Hope this helps!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM