1

I am dynamically creating a dropdown list of items using ngFor, looping through a string array (obtained from an SQL query), saved within a service.

<li *ngFor="let vehicleClasses of getVehicleClassList(); let i = index" (click)="toggleCheckBox(i)">
  <a>
    <input type="checkbox" id="vehCB_{{i}}"/>{{vehicleClasses}}
  </a>
</li>

The dropdown menu has a checkbox and then the name of the selection ({{VehicleClasses}}. How do I store which checkboxes the user has checked (and preferably from within the service rather than the component)?
Ideally, I want to have a boolean array which store the checkbox value. If it is possible, can I then bind the checkbox to a value so if, for example, a function were to change all the checkbox booleans, the checkboxes would update?

I've seen ngModel used in other similar scenarios - but I have not been able to successfully get it working.

2 Answers 2

4

At first, try to avoid using methods in bindings

*ngFor="let vehicleClasses of getVehicleClassList();

Every time change detection runs such methods are called and change detection runs very often. Assign the result to a property instead and bind to that property.

<li *ngFor="let vehicleClass of getVehicleClasses; let i = index" (click)="cbStatus[i] = !cbStatus[i]">
  <a>
    <input type="checkbox" [(ngModel)]="cbStatus[i]" />{{vehicleClass}}
  </a>
</li>
class MyComponent {
  @Input() set vehicleClasses(value) {
    this.vehicles = value;
    this.cbStatus = [];
    for(var p in this.vehicles) {
      this.vehicles.push(false);
    }
  }
}
Sign up to request clarification or add additional context in comments.

Comments

1

I apologise for posting an answer so quickly after posting the question. I could remove the question if preferred - but in case someone else hits a similar problem.

I didn't realise I could use ngModel to directly bind to a boolean array from within a service. Using ngFor's index notation, I could easy bind each checkbox to an element within the boolean array:

<li *ngFor="let vehicleClasses of getVehicleClassList(); let i = index" (click)="toggleCheckBox(i)">
  <a>
    <input type="checkbox" id="vehCB_{{i}}" [(ngModel)]="toolbarService.vehicleClassCheckboxes[i]"/>{{vehicleClasses}}
  </a>
</li>

The functions I wrote within the service that directly modify the boolean array caused the checkboxes to update correctly. If anyone else has a better way of doing this, I would love to know - although this happened to fit my scenario well.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.