Angular 2 checkbox check all

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>

Best Answer

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;
      });
    });
}