Refresh mat-checkbox in material data table on every call

Viewed 3213

I have select box and a data table with data, when I select the value from the select box, data will be generated and it will bind to checkbox of the data table which will be checked.., but the problem is if I select another value, then the new data which will be generated by this value will be checked as well as the old data from the previously selected value will be checked

Animals.ts file

   

 import {
      Component,
      OnInit
    } from '@angular/core';
    import {
      SelectionModel
    } from '@angular/cdk/collections';
    import {
      MatTableDataSource
    } from '@angular/material';


    export interface PeriodicElement {
      name: string;
      position: number;
      weight: number;
      symbol: string;
      state: boolean;
      selected: boolean;
    }

    @Component({
      selector: 'table-basic-example',
      styleUrls: ['table-basic-example.css'],
      templateUrl: 'table-basic-example.html',
    })
    export class TableBasicExample {
      animals = [];
      desiCow = []
      displayedColumns: string[] = ['select', 'position', 'name', 'weight', 'symbol'];
      dataSource = [{
          position: 1,
          name: 'Hydrogen',
          state: false,
          selected: false
        },
        {
          position: 2,
          name: 'Helium',
          state: false,
          selected: false
        },
        {
          position: 3,
          name: 'Lithium',
          state: false,
          selected: false
        },
        {
          position: 4,
          name: 'Beryllium',
          state: false,
          selected: false
        },
        {
          position: 5,
          name: 'Arsenic',
          state: false,
          selected: false
        },
        {
          position: 6,
          name: 'Barium',
          state: false,
          selected: false
        },
      ];
      ngOnInit() {
        this.getAnimalsType();
      }

     //get  animal type name
      getAnimalsType() {
        this.animals.push({
          id: 62,
          name: "desicow"
        }, {
          id: 63,
          name: "jersey"
        })
      }
 
     //select animal type for data to be checked
      selectAnimalType(event) {
        console.log(event, "evemt")
        // this.getanimalsQuestion(event);
        if (event == 62) {
          this.desiCow = []
          this.desiCow.push({
            position: 1,
            name: 'Hydrogen',
            state: false,
            selected: false
          }, {
            position: 4,
            name: 'Beryllium',
            state: false,
            selected: false
          })
        }
        if (event == 63) {
          this.desiCow = []
          this.desiCow.push({
            position: 2,
            name: 'Helium',
            state: false,
            selected: false
          }, {
            position: 3,
            name: 'Lithium',
            state: true,
            selected: true
          }, {
            position: 6,
            name: 'Barium',
            state: false,
            selected: false
          })
        }
        console.log(this.dataSource)
        this.mapObjectBasedOnAnimal(event)
      }

      //function to bind the check box
      mapObjectBasedOnAnimal(animalId) {
        for (let v = 0; v < this.desiCow.length; v++) {
          for (let k = 0; k < 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].state = true;
                this.dataSource[k].selected = this.desiCow[v].selected;
                this.dataSource[k].selected = true;
                console.log("success", this.dataSource[k]);
              }
            }
          }
        }
      }
    }
animals.html file
   

 <mat-grid-list cols="3" rowHeight="3:3">
      <form class="example-form" #form="ngForm" (ngSubmit)="mapAnimalType(form.value)">
        <mat-grid-tile>
          <h6 class="catTitle">Animal Type</h6>
        </mat-grid-tile>
        <mat-grid-tile>
          <mat-form-field>
            <mat-select required (selectionChange)="selectAnimalType(animal)" [(ngModel)]="animal" name="animal" placeholder="Select Animal Type">
              <mat-option *ngFor="let animal of animals" [value]="animal.id">
                {{animal.name}}
              </mat-option>
            </mat-select>
            <mat-error>Animal Type is required</mat-error>
          </mat-form-field>
        </mat-grid-tile>
        <mat-grid-tile>
          <button type="submit" [disabled]="!form.valid" mat-raised-button class="primary-button" color="primary">Submit</button>
        </mat-grid-tile>
      </form>
    </mat-grid-list>



    <table mat-table [dataSource]="dataSource" class="mat-elevation-z8">

      <!-- Checkbox Column -->
      <ng-container matColumnDef="select">
        <th mat-header-cell *matHeaderCellDef>
          <mat-checkbox [ngModel]="selected"></mat-checkbox>
        </th>
        <td mat-cell *matCellDef="let element; let i = index">
          <mat-checkbox [value]="element.position" [(ngModel)]="element.state"></mat-checkbox>
        </td>
      </ng-container>

      <!-- Position Column -->
      <ng-container matColumnDef="position">
        <th mat-header-cell *matHeaderCellDef> No. </th>
        <td mat-cell *matCellDef="let element"> {{element.position}} </td>
      </ng-container>

      <!-- Name Column -->
      <ng-container matColumnDef="name">
        <th mat-header-cell *matHeaderCellDef> Name </th>
        <td mat-cell *matCellDef="let element"> {{element.name}} </td>
      </ng-container>

      <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
      <tr mat-row *matRowDef="let row; columns: displayedColumns;" (click)="selection.toggle(row)">
      </tr>
    </table>

when the value is selected from the select box, then always new data should be checked on the data table

also below is the link for the code https://stackblitz.com/edit/angular-3kbmuh

Please help me to solve this thanks

2 Answers

You should reset the original data source items before you set the state of new items.

  selectAnimalType(event) {
    console.log(event, "evemt")

   this.dataSource.forEach(item=>item.state = false); //<--reset all items

    // this.getanimalsQuestion(event);
    if (event == 62) {
      this.desiCow = []
      this.desiCow.push({ position: 1, name: 'Hydrogen',             state: false, selected: false },
        { position: 4, name: 'Beryllium', state: false,                selected: false })
    }
    if (event == 63) {
      this.desiCow = []
      this.desiCow.push({ position: 2, name: 'Helium',                                state: false, selected: false },
        { position: 3, name: 'Lithium', state: true,                  selected: true },
        { position: 6, name: 'Barium', state: false,                   selected: false })
    }
    console.log(this.dataSource)
    this.mapObjectBasedOnAnimal(event)
  }

Working copy is here https://stackblitz.com/edit/angular-3kbmuh-szd399

Just use below line in SelectAnimalType().It will reset the datasource every time.

this.dataSource.forEach(item=>item.state = false); //<--reset all items

Related