samedi 20 octobre 2018

Collect checkboxes values (dynamically created) using Angular 6

I'm newbie on the Angular and I apologize if it's a dummy question, but anyway.

I have the following structure in Angular 6:

<form [formGroup]="form" novalidate (submit)="doStuff()">
  <table>
    <thead>
    <tr>
      <th>#</th>
      <th>Key</th>
      <th>Select</th>
    </tr>
    </thead>
    <tbody>
    <tr *ngFor="let user of users; index as i">
    <th></th>
    <td></td>
    <td><input type="checkbox" [formControl]="form.controls['selectedUsersGroup'].controls[i]"></td>
    </tr>
    </tbody>
  </table>
  <div>
    <a href="#"><button type="submit">Do</button></a>
  </div>
</form>

Basically I have a list of users, which my service returns and I want to get keys of only selected on the form users (clicked on the checkboxes).

In my component I created form and array of false values, associated with checkboxes (as no users are selected by default):

constructor(private formBuilder: FormBuilder) {
  this.usersSelected = new Array(10).fill(false);
  this.form = this.formBuilder.group({
    selectedUsersGroup: this.formBuilder.array(this.usersSelected)
  });
}

The interesting part is when I have to get keys of selected users. When clicked on submit button the following method is called:

doStuff() {

   //get checkboxes group
   this.usersSelected= this.form.get('selectedUsersGroup').value;

   //get indexes of selected checkboxes
   var indexes = [];
   var idx = this.usersSelected.indexOf(true);
   while (idx != -1) {
     indexes.push(idx);
     idx = this.usersSelected.indexOf(true, idx + 1);
   }

   //get keys of users by indexes of selected checkboxes
   var keys = [];
   for (var i = 0; i < indexes.length; ++i) {
     keys.push(this.users[indexes[i]].key);
   }
 }

This is working fine, but it looks too heavy, I'm pretty sure there is a more simple and elegant solution.

I would be glad if someone could point me on that)




Aucun commentaire:

Enregistrer un commentaire