title: Checkbox Issue for the Material Data Table
body: <p>I have Material data where the set of data is being displayed and also have the select box where based on select box data s being checked when the animal name is selected from the select box, the selected data from the array will be checked in the checkbox, this issue is when I try to un-check the checked id it is splicing the different id, not the id which I unchecked, and also while checking id has  also same issue. Please help to find the issue.</p>
  
  <p>animal.ts
  <div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>import {
    Component,
    OnInit
  } from '@angular/core';
  import {
    SelectionModel
  } from '@angular/cdk/collections';
  import {
    MatTableDataSource
  } from '@angular/material';
  
  
  export interface PeriodicElement {
    name: string;
    position: number;
    state: boolean;
    selected: boolean;
  
  }
  
  /**
   * @title Basic use of `&lt;table mat-table&gt;`
   */
  @Component({
    selector: 'table-basic-example',
    styleUrls: ['table-basic-example.css'],
    templateUrl: 'table-basic-example.html',
  })
  export class TableBasicExample {
    animals = [];
    desiCow = [];
    dataSource = [];
    checkedId = [];
    valueId = [];
    falCheckbox = [];
    checkEachObj = [];
    checked = false;
    mappedValue = false;
    displayedColumns: string[] = ['select', 'position', 'name'];
    ArrayOne = [{
      Key: "Category1",
      value: [{
          position: 1,
          name: 'Helium',
          state: false,
          selected: false
        },
        {
          position: 2,
          name: 'Lithium',
          state: false,
          selected: false
        },
        {
          position: 3,
          name: 'Barium',
          state: false,
          selected: false
        }
      ]
    }, {
      Key: "Category2",
      value: [{
          position: 4,
          name: 'Light',
          state: false,
          selected: false
        },
        {
          position: 5,
          name: 'Hydrogen',
          state: false,
          selected: false
        },
        {
          position: 6,
          name: 'Beryllium',
          state: false,
          selected: false
        }
      ]
    }]
    ngOnInit() {
      this.getAnimalsType();
    }
    getAnimalsType() {
      this.animals.push({
        id: 62,
        name: "desicow"
      }, {
        id: 63,
        name: "jersey"
      })
    }
    selectAnimalType(event) {
      console.log(event, "evemt")
      this.checkedId = [];
      this.valueId = [];
      this.falCheckbox = [];
      this.dataSource = [];
  
      this.ArrayOne.forEach(item =&gt; {
        for (let j = 0; j &lt; item.value.length; j++) {
          item.value[j].state = false;
          item.value[j].selected = false;
          this.dataSource.push(item.value[j])
        }
      })
      if (event == 62) {
        this.desiCow = []
        this.desiCow.push({
          position: 5,
          name: 'Hydrogen',
          state: true,
          selected: true
        }, {
          position: 6,
          name: 'Beryllium',
          state: true,
          selected: true
        })
      }
      if (event == 63) {
        this.desiCow = []
        this.desiCow.push({
          position: 1,
          name: 'Helium',
          state: true,
          selected: true
        }, {
          position: 2,
          name: 'Lithium',
          state: true,
          selected: true
        }, {
          position: 3,
          name: 'Barium',
          state: true,
          selected: true
        })
      }
      console.log(this.dataSource)
      this.mapObjectBasedOnAnimal(event)
    }
    mapObjectBasedOnAnimal(animalId) {
      console.log(this.dataSource, "desicow")
      console.log(this.desiCow, "desicow")
      this.desiCow.forEach(element =&gt; {
        // console.log(element,"elleleleel")
        if (element.position != undefined) {
          if (element.position) {
            if (this.checkedId.indexOf(element.position) &lt; 0) {
              this.checkedId.push(element.position)
              this.valueId.push(element)
            }
            console.log(this.valueId, "valueID")
          }
        }
        this.falCheckbox = this.valueId
      })
      for (let v = 0; v &lt; this.desiCow.length; v++) {
        for (let k = 0; k &lt; this.dataSource.length; k++) {
          if (this.dataSource[v] != undefined) {
            if (this.dataSource[k].position === this.desiCow[v].position) {
              this.dataSource[k].state = this.desiCow[v].state;
              this.dataSource[k].selected = this.desiCow[v].selected;
              console.log("success", this.dataSource[k]);
            }
          }
        }
      }
    }
    //function to select all for checkbox
    checkall(event, sbValue, i) {
      this.checked = event;
      sbValue.forEach(x =&gt; x.state = event)
      console.log(this.checkedId, "checkedaId before")
      if (event == true) {
        sbValue.forEach(item =&gt; {
          if (this.checkedId.indexOf(item.position) &lt; 0) {
            this.checkedId.push(item.position)
            this.valueId.push(item)
            item.selected = event;
          }
        })
        console.log(this.checkedId, "checed")
        this.falCheckbox = this.valueId
      } else if (event == false) {
        for (let i = 0; i &lt; this.falCheckbox.length;) {
          if (this.falCheckbox[i].position == this.checkedId[i]) {
            console.log(this.falCheckbox[i].position, "=====", this.checkedId[i])
            this.checkedId.splice(i, 1)
            this.falCheckbox.splice(i, 1)
          }
          console.log(this.checkedId, "fal after clear")
        }
        for (let i = 0; i &lt; this.falCheckbox.length;) {
          if (this.falCheckbox[i].position == this.checkedId[i]) {
            console.log(this.falCheckbox[i].position, "=====", this.checkedId[i])
            this.checkedId.splice(i, 1)
            this.falCheckbox.splice(i, 1)
          }
          console.log(this.checkedId, "fal after clear")
        }
  
      }
    }
    //function to select each for checkbox
    checkEach(item, i, event) {
      console.log(item, event)
      if (event.checked == true) {
        if (this.checkedId.indexOf(item.position) &lt; 0) {
          this.checkedId.push(item.position)
          this.checkEachObj.push(item);
          item.selected = event.checked;
        }
      }
      this.falCheckbox = this.checkEachObj
      console.log(this.falCheckbox, "falcheckbox", this.checkedId)
      if (event == false) {
        const index = this.falCheckbox.indexOf(i);
        this.checkedId.splice(index, 1)
        console.log(this.checkedId, "checkediddd for each")
      }
    }
  }</code></pre>
  </div>
  </div>
  </p>
  
  <p>In the above code, I have code for check all the checkbox or check each box, both have the same issue, I am not able to find the correct solution for it </p>
  
  <p>Animal.html
  </p>
  
  <pre><code>&lt;mat-grid-list cols="3" rowHeight="3:3"&gt;
    &lt;form class="example-form" #form="ngForm" (ngSubmit)="mapAnimalType(form.value)"&gt;
      &lt;mat-grid-tile&gt;
        &lt;h6 class="catTitle"&gt;Animal Type&lt;/h6&gt;
      &lt;/mat-grid-tile&gt;
      &lt;mat-grid-tile&gt;
        &lt;mat-form-field&gt;
          &lt;mat-select required (selectionChange)="selectAnimalType(animal)" [(ngModel)]="animal" name="animal" placeholder="Select Animal Type"&gt;
            &lt;mat-option *ngFor="let animal of animals" [value]="animal.id"&gt;
              {{animal.name}}
            &lt;/mat-option&gt;
          &lt;/mat-select&gt;
          &lt;mat-error&gt;Animal Type is required&lt;/mat-error&gt;
        &lt;/mat-form-field&gt;
      &lt;/mat-grid-tile&gt;
      &lt;mat-grid-tile&gt;
        &lt;button type="submit" mat-raised-button class="primary-button" color="primary"&gt;Submit&lt;/button&gt;
      &lt;/mat-grid-tile&gt;
    &lt;/form&gt;
  &lt;/mat-grid-list&gt;
  
  &lt;div *ngFor="let sb of ArrayOne; let in = index"&gt;
    &lt;h5 class="sb__key"&gt;key:- {{sb.Key}}&lt;/h5&gt;
    &lt;table mat-table [dataSource]="sb.value" class="mat-elevation-z8"&gt;
  
      &lt;!-- Checkbox Column --&gt;
      &lt;ng-container matColumnDef="select"&gt;
        &lt;th mat-header-cell *matHeaderCellDef&gt;
          &lt;mat-checkbox [ngModel]="sb.value[in]?.selected" (ngModelChange)="checkall($event,sb.value,in)"&gt;&lt;/mat-checkbox&gt;
        &lt;/th&gt;
        &lt;td mat-cell *matCellDef="let element; let i = index"&gt;
          &lt;mat-checkbox [value]="element.position" [(ngModel)]="element.state" (change)="checkEach(element,i,$event)"&gt;&lt;/mat-checkbox&gt;
        &lt;/td&gt;
      &lt;/ng-container&gt;
  
      &lt;!-- Position Column --&gt;
      &lt;ng-container matColumnDef="position"&gt;
        &lt;th mat-header-cell *matHeaderCellDef&gt; No. &lt;/th&gt;
        &lt;td mat-cell *matCellDef="let element"&gt; {{element.position}} &lt;/td&gt;
      &lt;/ng-container&gt;
  
      &lt;!-- Name Column --&gt;
      &lt;ng-container matColumnDef="name"&gt;
        &lt;th mat-header-cell *matHeaderCellDef&gt; Name &lt;/th&gt;
        &lt;td mat-cell *matCellDef="let element"&gt; {{element.name}} &lt;/td&gt;
      &lt;/ng-container&gt;
  
      &lt;tr mat-header-row *matHeaderRowDef="displayedColumns"&gt;&lt;/tr&gt;
      &lt;tr mat-row *matRowDef="let row; columns: displayedColumns;" (click)="selection.toggle(row)"&gt;
      &lt;/tr&gt;
    &lt;/table&gt;
  &lt;/div&gt;
  </code></pre>
  
  
  
  <p>below is the link for the running code 
  <a href="https://stackblitz.com/edit/angular-3kbmuh-g3eepr" rel="nofollow noreferrer">https://stackblitz.com/edit/angular-3kbmuh-g3eepr</a></p>
  
  <p>Thanks</p>