Skip to content
Advertisement

Select All checkbox Angular material 5 | Gmail style if selecting individual it will also select

I need to create a select all functionality in angular material, I am sharing code below which is partially working.

<section *ngFor="let ing of pizzaIng; let i = index" class="example-section">
  <mat-checkbox (change)="selectChildren()"
     [(ngModel)]="ing.checked">
    {{ing.name}}
  </mat-checkbox>
</section>
  <mat-checkbox (change)="updateCheck()"
      class="example-margin"
      [(ngModel)]="selectAll">
    Select All
  </mat-checkbox>

.ts file

export class CheckboxConfigurableExample {
    pizzaIng: any;
    selectAll = false;

    constructor() {
        this.pizzaIng = [{
                name: "Pepperoni",
                checked: false
            },
            {
                name: "Sasuage",
                checked: true
            },
            {
                name: "Mushrooms",
                checked: false
            }
        ];
    }


    selectChildren() {

        for (var i = 0; i < this.pizzaIng.length; i++) {
            if (this.pizzaIng[i].checked === true) {
                return this.selectAll = true;
            } else {
                return this.selectAll = false;
            }

        }
    }




    updateCheck() {
        console.log(this.selectAll);
        if (this.selectAll === true) {
            this.pizzaIng.map((pizza) => {
                pizza.checked = true;
            });

        } else {
            this.pizzaIng.map((pizza) => {
                pizza.checked = false;
            });
        }
    }
}  

select all/deselect is working but the individual selection is not working properly, if selected the first one it is selecting the select all but it should work when selected all individual, Please help.

Advertisement

Answer

Just change your selectchildren to this, using every will check all the checkboxes are checked, and it should work fine. You already have a checked property which has the values as checked or not, you can check if all entries are checked then youc an enable the selectAll, else disable it.

  selectChildren() {    
    if (this.pizzaIng.every(a => a.checked)) {
      this.selectAll = true;
    } else {
      this.selectAll = false;
    }
  }

Here is the demo

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement