Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular 2 checkbox to select all

Problem

I looked for answers to this problem but I'm still stuck I have a table with multiple rows with a checkbox on every row, I need a checkbox to select all and deselect all, here some example code

Template

<table class="table table-bordered table-condensed table-striped table-hover">
<thead>
    <tr>
        <th></th>
        <th>Size</th>
        <th>Diameter</th>
        <th class="text-center">
            <input type="checkbox" name="all" (change)="checkAll($event)"/>
        </th>
    </tr>
</thead>
<tbody>
    <tr *ngFor="let size of sizes | async ; let i = index">
        <td class="text-right">{{i + 1}}</td>
        <td class="text-right">{{size.size}}</td>
        <td>{{size.diameter}}</td>
        <td class="text-center">
            <input type="checkbox" name="sizecb[]" value="{{size.id}}"/>
        </td>
    </tr>
</tbody>

Component

    export class ListSizeComponent implements OnInit {
    constructor () {
    }

    sizes: any;

    setSizes() {
        this.sizes = [
            {'size': '0', 'diameter': '16000 km'},
            {'size': '1', 'diameter': '32000 km'}
        ]
    }

    checkAll(ev) {
        if (ev.target.checked) {
            console.log("True")
        } else {
            console.log("False");
        }
    }

    ngOnInit(): void {
        this.setSizes();
    }
}
like image 853
Lupo Wolfman Solitario Avatar asked Sep 18 '16 16:09

Lupo Wolfman Solitario


1 Answers

You can leverage ngModel to do that.

Template:

<input type="checkbox" name="all" [checked]="isAllChecked()" (change)="checkAll($event)"/>
....
<input type="checkbox" name="sizecb[]" value="{{size.id}}" [(ngModel)]="size.state"/>

Component:

checkAll(ev) {
  this.sizes.forEach(x => x.state = ev.target.checked)
}

isAllChecked() {
  return this.sizes.every(_ => _.state);
}

Stackblitz Example

like image 74
yurzui Avatar answered Oct 07 '22 20:10

yurzui