0

I have a checkbox list control and am trying to get checked values into an array.

My models:

export class Order {
    Products: Product[];
    SelectedProducts: string[];
}

export class Product {
    Id: number;
    Title: string;
}

The snippet goes through the Product property and displays them as checkboxes:

    <div *ngFor="let product of orderService.order.Products">

        <label>
            <input type="checkbox" name="orderService.order.Products" value="{{product.Id}}" [(ngModel)]="product.checked" />
            {{product.Title}}
        </label>

    </div>

I can get the list of orderService.order.Products values from the checkboxes but how to filter them to get only checked values when submitting?

I based my code on the @ccwasden answer here: Angular 2: Get Values of Multiple Checked Checkboxes but my Product model does not have the checked property and it shouldn't have.

In my component I have:

get selectedOptions() {
    return this.orderService.order.Products
        //.filter(opt => opt.checked)
        .map(opt => opt.value)
}

submitorder(form: NgForm) {
    var selection = this.selectedOptions;

    [post order here]
}

but selectedOptions comes empty.

EDIT

This is the correct code for selectedOptions() method (note opt.Id not opt.value as above):

get selectedOptions() {
    return this.orderService.order.Products
        //.filter(opt => opt.checked)
        .map(opt => opt.Id)
}

But the main question remains - how to get checked options?

nickornotto
  • 1,946
  • 4
  • 36
  • 68

1 Answers1

0

You've made a small mistake. Fix:

get selectedOptions() {
    return this.orderService.order.Products
        .filter(opt => opt['checked'])
        .map(opt => opt.Id);
}

Each 'opt' is a 'Product', so they don't have a 'value'.

On the other hand, I don't think value="{{product.Id}}" adds anything to the functionality as ngModel is actually the value of the input tag. Hope this helps :)

EDIT: If checked is not part of the model then simply write product['checked'] instead of product.checked.

slashpm
  • 214
  • 2
  • 9
  • Thanks @slashpm but that wasn't my question. Yes indeed it is `opt.Id` originally, I pasted the wrong code here, but still don't know how to get checked values. `opt.checked` in filter will not build because the model does not have `checked` property – nickornotto Jun 27 '18 at 14:23