TobiDevloft
TobiDevloft

Reputation: 301

How can I access the checked property of a checkbox which is indexed by an *ngFor loop - Angular

I have a list of drop-down elements, which is indexed by an *ngFor loop.

<div class="item-wrapper" *ngIf="showItems">
  <div class="wrap-collapsible" *ngFor="let item of items; let i = index">
    <input id="{{i}}" class="toggle" type="checkbox">
    <label for="{{i}}" class="dropdown-toggle" tabindex="0" (click)="selectItem(item)">
      Threat {{item.id}}: {{item.category}}
    </label>
    <div class="collapsible-content">
      <div class="content-wrapper">
        <p class="title">{{item.title}}</p>
      </div>
    </div>
  </div>
</div>

Per default, the checkbox input is selected on click, and stays checked when selecting other elements.

How would I go about unchecking all elements except the last one clicked?

I've tried doing...

<input id="{{i}}" type="checkbox" [checked]="i == selectedElement">

...while passing the index in the selectItem() method, where selectedElement is set to i. This doesn't work, because then no item is selectable.

Can anyone give me a push in the right direction?

Upvotes: 0

Views: 131

Answers (1)

user4676340
user4676340

Reputation:

Bind to the change function of your input :

<input id="{{i}}" class="toggle" type="checkbox" (change)="setLastClicked(item)">

In your TS :

setLastClicked(item) {
  this.lastSelected = item;
}

You can now use that memory reference to compare to the items when you [un]check them all :

toggleCheck() {
  this.items.forEach(item => item.checked = {
    if(item === this.lastSelected) return;
    item.checked = !item.checked;
  });
}

With a memory reference, you don't need the ID anymore.

Upvotes: 1

Related Questions