mercredi 21 juin 2017

How to set a checkbox's checked-attribute via its changed-eventlistener

I have a matrix in angular.js (with material.angular) which is filled with checkboxes. When the user clicks a checkbox, a HTTP-Request is send to backend server. In case the backend server is not available or the service call goes wrong for any reason, I want the checkbox to return to it's previous state (checked/unchecked). Therefore I implemented the following change-eventhandler to make the service call and react dependent on the result of the service call:

zuordnungChanged(rolle_id: string, recht_id: string) {
let a = this.zuordnungsmatrix["Rolle_" + rolle_id + "_Recht_" + recht_id];
if (a === true ){
  this.rechtematrix.rechtEntziehen(rolle_id, recht_id).subscribe(() => {
      a = false;
      this.zuordnungsmatrix["Rolle_" + rolle_id + "_Recht_" + recht_id] = a;
      //Notify user
      });
    },
    () => {
      //Notify user
    });
} else {
  this.rechtematrix.rechtVergeben(rolle_id, recht_id).subscribe(() => {
      a = true;
      this.zuordnungsmatrix["Rolle_" + rolle_id + "_Recht_" + recht_id] = a;
      //Notify User
      });
  },
    () => {
      //Notify user
    }
  );
}
}

The zuordnungsmatrix variable is defined and filled like that:

private zuordnungen: Array<any>;
  private zuordnungsmatrix = [];

erstelleZuordnungsmatrix(): void {
    for (let rolle of this.zuordnungen) {
      for ( let recht of rolle.recht_ids) {
        this.zuordnungsmatrix["Rolle_" + rolle.rolle_id + "_Recht_" + recht] = true;
      }
    }
  }

I bound the values from zuordnungsmatrix to the checkbox' checked-attribute like this:

<table td-data-table *ngIf="rechteUndRollenVorhanden()">
      <tr>
        <th td-data-table-column></th>
      <th td-data-table-column *ngFor="let rolle of rollen" [id]="'Rolle_' + rolle.rolle_id"></th>
      </tr>
      <tr td-data-table-row *ngFor="let recht of rechte" [id]="'Recht_' + recht.recht_id">
        <td td-data-table-cell></td>
        <td td-data-table-cell *ngFor="let rolle of rollen">
          <md-checkbox [id]="'Rolle_' + rolle.rolle_id + '_Recht_' + recht.recht_id"
                       [checked]="zuordnungsmatrix['Rolle_' + rolle.rolle_id + '_Recht_' + recht.recht_id] ? true : false"
                        (change)="zuordnungChanged(rolle.rolle_id, recht.recht_id, $event)">
          </md-checkbox>
        </td>
      </tr>
    </table>

My problem know is that I don't know how to let the checkboxes represent the actual state of zuordnungsmatrix. The variable is updated and this binding in the view works as well:



But I tried a lot to update the checkbox but It didn't work. How can I update a checkbox' state in its own eventlistener?




Aucun commentaire:

Enregistrer un commentaire