Dheeraj Agrawal Dheeraj Agrawal - 5 months ago 117
AngularJS Question

Make select/unselect all functionality in angular 2

I am new to angular 2 & trying to create select/unselect all checkboxes. I have a table like this:

<table>
<thead>
<tr>
<th><input type="checkbox" name="selectAll"></th>
<th>Name</th>
<th>Number</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="checkbox"></td>
<td>abc</td>
<td>9876373773</td>
</tr>
<tr>
<td><input type="checkbox"></td>
<td>abc</td>
<td>9876373773</td>
</tr>
<tr>
<td><input type="checkbox"></td>
<td>abc</td>
<td>9876373773</td>
</tr>
</tbody>
</table>


So if user clicks on selectAll checkbox other checkboxes should get check to. Data is coming dynamically, here is my api call:

this.contactService.getName(this.pageNumber, this.pageSize)
.subscribe(
data => {
this.contactlist = data.results;
},
err => console.error(err),
() => console.log('Contact list fetched')
);

Answer

With data-driven table you could achieve this by updating row-model's "checked" flag. For example you could do something like this:

<table>
    <thead>
        <tr>
            <th><input type="checkbox" name="selectAll" [checked]="toggle" (change)="toggleAll()"></th>
            <th>Name</th>
            <th>Number</th>
        </tr>
    </thead>
    <tbody>
        <tr *ngFor="let item of items">
            <td><input type="checkbox" [checked]="item.checked" (change)="toggleItem(item)"></td>
            <td>{{ item.name }}</td>
            <td>{{ item.number }}</td>
        </tr>
    </tbody>
</table>

And then in component:

toggle = false

items = [
  { name: 'aaa', number: '3452342343' },
  { name: 'aaa', number: '3452342343' }
]

toggleItem(item) {
  item.checked = !item.checked
  this.toggle = this.items.every(item => item.checked)
}

toggleAll() {
  this.toggle = !this.toggle
  this.items.forEach(item => item.checked = this.toggle)
}

Note that this is important that you also handle cases when you check all checkboxes manually and it should automatically check checkAll checkbox. And vise versa.

Demo: http://plnkr.co/edit/Nw8Wk0kXSbQLkAE7yW0e?p=info