Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 checkbox check all

Tags:

angular

I have a list to check projectnames. On the bottom I want to place a checkbox to check or uncheck them all. I think I need an *ngIf (if checked) with an *ngFor loop (check all) but this is quite the challenge... I cannot figure out how I should procede with this. Do I use (checked) or something or *ngIf="(checked)" and then use an *ngFor loop to set project.isChecked. I cannot get inside the logic of this.

<div id="drp-project-select">
        <div class="scroller" [hidden]="!showMenu">
            <div id="search-wrapper">
                <i class="fa fa-search fa-xs"></i>
                <input [(ngModel)]="searchTerm" type="text" placeholder="Zoek op naam..." #search>
            </div>   
            <ul>
                <li *ngFor="#project of projectdata.LoginResponse?.ProjectVM | searchpipe:'Project':search.value">
                    <label class="checkbox-label" >
                        <input type="checkbox" class="dropdown-checkbox" [(ngModel)]="project.isChecked" (change)="addProject(project)" >
                        <span>{{project.Project}}</span>
                    </label>
                </li>
            </ul>
        </div>
        <div class="bottom-data" [hidden]="!showMenu">
            <label><input type="checkbox" id="bottom-checkbox"></label>
        </div>
    </div>
like image 364
JanVanHaudt Avatar asked Feb 25 '16 13:02

JanVanHaudt


People also ask

How do you check checkbox is checked or not in angular 8?

The ng-checked Directive in AngularJS is used to read the checked or unchecked state of the checkbox or radio button to true or false. If the expression inside the ng-checked attribute returns true then the checkbox/radio button will be checked otherwise it will be unchecked.


1 Answers

I would use a control on the "check / uncheck all" checkbox to be notified when the user checks or unchecks:

<input type="checkbox" [ngFormControl]="allCtrl"/>

allCtrl is initialized within the constructor of the component. Then you could register against the valueChanges property of this control to be notified of updates and update the isChecked fields accordingly:

constructor() {
  this.allCtrl = new Control();
  this.allCtrl.valueChanges.subscribe(
    (val) => {
      this.projectdata.LoginResponse.ProjectVM.forEach((project) => {
        project.isChecked = val;
      });
    });
}
like image 126
Thierry Templier Avatar answered Sep 22 '22 23:09

Thierry Templier