pdace
pdace

Reputation: 467

Angular 2: Change Some Text Depending on the Checkbox

I'm really new to Angular 2 and I've been playing around with it to learn it. I was trying to change some text on the screen depending on a boolean value.

Let's say I have a toggle checkbox and I want to switch back and forth between some text on the screen depending on the toggle button.

<div class="ui toggle checkbox">
  <input type="checkbox" [(ngModel)]="version2" name="versionControl">
  <label>version2</label>
</div>
{{versionText}}

And the component would be something like this

export class AppComponent {
  version2:boolean=false;
  versionText= this.version2 ?  "This is Version 1:" : "Switched to Version 2"
  ...
}

Of course it doesn't work since I'm assigning the value at start and at the beginning, version2 is false and even if the boolean value changes later, the text doesn't since I'm not assigning it again, I guess..

I know I can do it with some sort of onClick function (or something similar) on checkbox but I just want to know if there is an easier and more "Angular" way of accomplishing this.

Upvotes: 2

Views: 6005

Answers (1)

ulou
ulou

Reputation: 5853

You can use ngIf:

<div class="ui toggle checkbox">
  <input type="checkbox" [(ngModel)]="version2" name="versionControl">
  <label *ngIf="verion2">This is Version 1:</label>
  <label *ngIf="!verion2">Switched to Version 2</label>
</div>

or just

<div class="ui toggle checkbox">
  <input type="checkbox" [(ngModel)]="version2" name="versionControl">
  <label>{{versionText}}</label>
</div>

Upvotes: 2

Related Questions