Search code examples
angularshow-hideangular-ng-if

How to hide and show content using *ngIf


I have some problems with *ngIf in Angular. How do I hide my content again?

In my example at Stackblitz, I'd like to hide my content again after the two radio buttons are not active.

When I click "2" and "at home", my output shows. But I want it to disappear again if, for example, I say "in the gym".

https://stackblitz.com/edit/angular-hcmstg

Here I give the ngModel

<label class="radio-inline"><input [(ngModel)]="split2" type="radio" name="radio1" value="two">2</label>
<label class="radio-inline"><input [(ngModel)]="split3" type="radio" name="radio1" value="three">3</label>
<label class="radio-inline"><input [(ngModel)]="split4" type="radio" name="radio1" value="four">4</label>



<label class="radio-inline"><input [(ngModel)]="home1" type="radio" name="radio2" value="home">at home</label>
<label class="radio-inline"><input [(ngModel)]="gym1" type="radio" name="radio2" value="gym">in the gym</label>

and here I work with * ngIf

<tr>
    <th scope="row">1</th>
    <td *ngIf="split2 && home1">{{home[0][0][1]}}</td>
    <td *ngIf="split2 && home1">{{home[0][0][0]}}</td>
    <td *ngIf="split2 && home1">{{home[0][1][0]}}</td>
</tr>

but they won't hide If I click on another radio button. The output stays forever


Solution

  • The problem is that the models are only mapping the values, they don’t actually care if the element stays selected. So what you need to do is reuse the same model multiple times and have the input elements set different values depending on what you have selected.

    For example, you could modify your inputs like this:

    <label><input [(ngModel)]="repeats" type="radio" name="repeats" value="2">2</label>
    <label><input [(ngModel)]="repeats" type="radio" name="repeats" value="3">3</label>
    <label><input [(ngModel)]="repeats" type="radio" name="repeats" value="4">4</label>
    
    <label><input [(ngModel)]="location" type="radio" name="location" value="home">at home</label>
    <label><input [(ngModel)]="location" type="radio" name="location" value="gym">in the gym</label>
    

    The first group will set the model property repeats to either 2, 3, or 4. The second group will set the model property location to either home or gym.

    With that information, you can then adjust your conditions:

    <tr>
      <th scope="row">1</th>
      <td *ngIf="repeats == 2 && location == 'home'" (change)="show == !show">{{home[0][0][1]}}</td>
      <td *ngIf="repeats == 2 && location == 'home'">{{home[0][0][0]}}</td>
      <td *ngIf="repeats == 2 && location == 'home'">{{home[0][1][0]}}</td>
    </tr>
    

    So basically, you now only check for the two properties repeats and location. When the selection of the radio buttons change, then those two properties will also update and the conditions will be re-evaluated.