Miguel Frias
Miguel Frias

Reputation: 2710

Angular Material Checkbox doesn´t change state of checked

I´m working with a list of element and filtering the list using pipes, the filter is multi-selection to filter using more than one value, i save the filter in the localstorage to have persistent in the filter after close the window or reload the page, in the mat-checkbox component i use i function in the [checked]="existInArray(color.id, filterColor)" directive to check the checkbox if the value is already in the filter array to check the checkbox, but i have a problem, if the checkbox is checked using the function, the next time i click the checkbox to uncheck it, the checkbox doesnt change the state of checked true to false, only when i clicked a second time change to checked false

Template

<mat-checkbox *ngFor="let color of filterService.getFilter(filterType.FILTER_COLOR).items.ToArray() | filterQuery:filterOptions.color"
  [checked]="existInArray(color.id, filterColor)" class="filter-checkbox" [value]="color.id" [hidden]="color.id === '999999'"
  (click)="filterBy(filterType.FILTER_COLOR, color.id, filterColor)">
  <div class="assigned">
    <div class="assigned-avatar text-center" [ngStyle]="{ 'background-color': color?.color?.bgColor }"></div>
    <p class="assigned-name">{{ color.name }}</p>
  </div>
</mat-checkbox>

Filter.ts

  public existInArray(element, array: Array<string>): boolean {
    return array.indexOf(element) > -1;
  }

  public filterBy(filterType: FilterTypeEnum, element: any, array: Array<string>) {
    this.toggleInArray(element, array);
    this.updateFilterObservable(filterType);
  }

enter image description here

Example, as you can see in the image, the checkbox is already checked by default because i use the existInArray function to check if the value of the check already exist in the filter array, if i try uncheck it, the first time doesn´t work, but when i click a second time the checkbox is unchecked, any idea what could be....?

I think the reason is because the [checked] is trigger before i toggle the element from the array, but no idea so far idea how to solved.... any idea.

Upvotes: 2

Views: 4440

Answers (2)

Mohammed Hussain
Mohammed Hussain

Reputation: 27

Top_Select: any[] = []; // selection clear when selected... in your ts file

//on the check_click event firing add this make sure you get the index (index_chkbx) in the event

this.Top_Select[index_chkbx] = true;

in you html

Upvotes: -1

Marshal
Marshal

Reputation: 11081

This is a timing issue of your [checked]="existInArray(color.id)" being out of sync with your click event.... [checked]="existInArray(color.id)" happens before your click. Subscribe to the change event instead.

(change)="toggleInArray(color.id)"

Upvotes: 9

Related Questions