mercredi 27 juin 2018

Get selected checkboxes values in Angular 5

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="" [(ngModel)]="product.checked" />
            
        </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.




Aucun commentaire:

Enregistrer un commentaire