Jean
Jean

Reputation: 621

Angular: how to manage a single checked box in a *ngFor

Hi there I've displayed a list of items with a checkbox in it.

I want the user to able to click this checkbox for only one of the item. It will uncheck the previously checked checkbox.

<tr *ngFor="let item of items>
 <td>
    <input type="checkbox value = "{{ item[i] }}">
  </td>
</tr>

I've tried everything I knew but I cant make it. If I check a box, the other one will remain checked.

1- Is it possible to do what I want? 2- How can I do?

Upvotes: 2

Views: 1339

Answers (1)

Saurabh Yadav
Saurabh Yadav

Reputation: 3386

It is better to use radio button in this case.

But you can programmatically control the behaviour of checkbox so only one checkbox is selected at a time.

You can look out this demo, this may helps you

Template file

<ul>
  <ng-container *ngFor="let item of items">
    <li>
      <input 
         type="checkbox" 
        [value]="item.value"
        [checked]="item.isChecked"
        (change)="onChange($event);"
        > {{item.label}}
    </li>
  </ng-container>
</ul>

Class file:

maintain a isChecked property in item list and bind it to check attribute in input element, then bind change event on input element whenever use change the change handler i.e onChange will trigger, then iterate on item and reinit the isChecked property expect currently check item.

items = [
      {'label': 'A', 'value': 'A', isChecked: false},
      {'label': 'B', 'value': 'B', isChecked: false},
      {'label': 'C', 'value': 'C', isChecked: false},
      {'label': 'D', 'value': 'D', isChecked: false},
      {'label': 'E', 'value': 'E', isChecked: false},
      {'label': 'F', 'value': 'F', isChecked: false},
      {'label': 'G', 'value': 'G', isChecked: false}
    ]; 

  onChange(event: any) { 
    const {checked, value} = event.target;
    let index = this.items.length;
    while(index--) {
       this.items[index].isChecked = value === this.items[index]['value'];
    }
  }

Upvotes: 3

Related Questions