jeudi 25 octobre 2018

Binding checkboxes directly to a ngModel's list of ids

I have a model which contains a list of ids. I have a set of checkboxes whose values are ids. I want to bind them together directly, but all I've managed to do is to manually hook into the [checked] and (change) attributes which seems like more work than I should be doing. (That is, lower-level interfacing between a model and the component for functionality which is so basic that it seems like it should already be supported out-of-the-box.)

The model:

export class Product {
  id: number;
  name: string;
}
export class MyModel {
  products: number[];
  // plus other unrelated stuff of course
}

Then in my component, I have a series of checkboxes (I'm using mat-checkbox, but that shouldn't matter), where the display value is the product name, and the value is the id.

<mat-checkbox *ngFor="let product of products"
              [value]="product.id"></mat-checkbox>

What I'm trying to do, is to to populate the products array in the model with the collection of selected checkboxes values. Eg if products 1,3,5 are checked, the model's products array would be [1,3,5].

I know I can get this working if I bind [checked] to a function that looks to see if the model's array contains the id, and the (change) event to a function that pushes the value to the array. For example:

<mat-checkbox *ngFor="let product of products"
  [value]="product.id"
  (change)="$event.checked ? model.products.push(product.id) : model.products.splice(model.products.indexOf(product.id),1)"
  [checked]="model.products.includes(product.id)"></mat-checkbox>

But this is pretty nasty, especially that change event. Is it possible to simply bind the component directly to the ngModel itself? Some syntax I'm possibly not aware of?

The list of products




Aucun commentaire:

Enregistrer un commentaire