How to uncheck mat checkbox in angular 14

2.9k Views Asked by At

Trying to recheck the mat checkbox but not working. in my application after clicking the "Select Checkbox Car and Bus" button click on the input box and check the Bus and Car then click the cancel button of Bus and Car. again click the input field, now see the check boxes of Bus and Car unchecked but here checked. So In this condition how to uncheck the check boxes.

mauto.component.ts:

  removeChip = (data: any | ItemData): void => { 
    this.toggleSelection(data); 
  };

 
  toggleSelection = (data: ItemData): void => {
    data.selected = !data.selected; 
    if (data.selected === true) { 
      if (!this.selectData.find(({ item }) => item === data.item)) {
        this.selectData.push(data); 
      }  
    } else {
      const i = this.selectData.findIndex(value => value.item === data.item);
      this.selectData.splice(i, 1);
    } 
    this.selectControl.setValue(this.selectData);
    this.emitAdjustedData();
   };

Demo : https://stackblitz.com/edit/angular-ivy-gzubna?file=src%2Fapp%2Fshared%2Fmauto%2Fmauto.component.ts

1

There are 1 best solutions below

8
Nehal On BEST ANSWER

You need to keep the chips and checkboxes in sync. So, when a chip is removed by clicking cancel, it should also uncheck the item, which should resolve the issue you are having.

toggleSelection = (data: ItemData): void => {
    data.selected = !data.selected;
  ​
    if (data.selected === true) {
      this.selectData.push(data);
    } else {
      let i = this.selectData.findIndex(value => value.item === data.item);
      this.selectData.splice(i, 1);
      
      i = this.rawData.findIndex(x => x.item === data.item)
      this.rawData[i].selected = false;
    }

    this.selectControl.setValue(this.selectData);
    this.emitAdjustedData();
  };

Demo