-3

I want to show the full table when the 'all' radio button is clicked. I want to show the row containing only 'male' when the male radio button is clicked. And I want to show the row containing only 'female' when the female radio button is clicked. All it shows is a blank page. My code is:

<form>
    <input type="radio" name="r" [(ngModel)] = "chk1"> All
    <input type="radio" name="r" [(ngModel)] = "chk2"> male
    <input type="radio" name="r" [(ngModel)] = "chk3"> female
</form>

<table>
    <tr>
        <th>Name</th>
        <th>Gender</th>
    </tr>
    <tr *ngIf = "(chk1 || chk2">
        <td>abc</td>
        <td>male</td>
    </tr>
    <tr *ngIf = "chk1 || chk3">
        <td>xyz</td>
        <td>female</td>
    </tr>
</table>
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Boidurja Talukdar
  • 676
  • 2
  • 21
  • 42

1 Answers1

1

That's not how you're supposed to use radio buttons. All inputs should be bound to the same variable, but have a different value:

  <form>
    <label><input type="radio" name="o" value="all" [(ngModel)]="option" /> All</label>
    <label><input type="radio" name="o" value="male" [(ngModel)]="option" /> Male</label>
    <label><input type="radio" name="o" value="female" [(ngModel)]="option" /> Female</label>
  </form>

  Chosen option: {{ option }}

This way, you can use

*ngIf="option === 'male' || option === 'all'"

or

*ngIf="option === 'female' || option === 'all'"

Note that doing it like this is pretty inefficient. You'd better create a filtered copy of the array every time the option changes, from your controller (thanks to (ngModelChange)="createFilteredCopy()"), and then iterate on the filtered copy, without using any ngIf.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255