The state of the checked value remains unaffected when using the Angular Material Checkbox

I am currently working on a list of elements and implementing a filter using pipes. The filter allows for multi-selection, so users can filter the list by more than one value at a time. To ensure that the filter persists even when the window is closed or the page is reloaded, I save the filter in the local storage.

Within the mat-checkbox component, I utilize a function in the

[checked]="existInArray(color.id, filterColor)"
directive to determine whether a checkbox should be checked based on whether its corresponding value already exists in the filter array. However, I have encountered an issue - when I click on a checkbox to uncheck it after it has been checked programmatically, the state does not change from "checked" (true) to "unchecked" (false) immediately. It only changes after clicking on the checkbox for a second time.

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);
}

https://i.stack.imgur.com/wEubO.png

In the provided example image, you can see that the checkbox is already checked by default. This is because I utilize the existInArray function to check if the value of the checkbox already exists in the filter array. However, when attempting to uncheck the checkbox, it does not work on the first click. It only changes its state to unchecked after clicking on it a second time. Any suggestions on what might be causing this issue?

I suspect that the [checked] directive is triggered before toggling the corresponding element in the array. However, I am unsure how to resolve this issue at the moment. Any ideas would be much appreciated.

Answer №1

There seems to be a synchronization problem with the timing of your

[checked]="existInArray(color.id)"
and the click event. The
[checked]="existInArray(color.id)"
gets executed before your click event fires. To resolve this issue, you can consider subscribing to the change event instead.

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

Answer №2

BestPicks: any[] = []; // empty array for selected items in your typescript file

// When the check_click event is triggered, make sure to get the index (index_chkbx) from the event

this.BestPicks[index_chkbx] = true;

In your HTML:

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to send an action based on the HTTP method being used?

I've been utilizing NGXS for handling state in my angular project. What would be considered a best practice? Should I make the HTTP call first and then dispatch an action within its subscription? Or should I dispatch the action first and then make t ...

Express (generator) is failing to load custom scripts located in the public folder

I'm new to node and express and I'm facing a problem. I want to load a custom script.js from the public folder, but it's not loading. There are no errors in the console or anything in the network tab. When I try to access the URL localhost:3 ...

Conceal the div element if the screen size drops below a certain threshold

Is it possible to hide a div element when the browser width is less than or equal to 1026px using CSS, like this: @media only screen and (min-width: 1140px) {}? If not, what are some alternative solutions? Additional information: When hiding the div eleme ...

Using a combination of radio buttons and JavaScript to adjust the color of a div element

Currently, I am experimenting with radio buttons to modify the background color of my div tag. My goal is to incorporate more than one condition. For example, if button A and button B are both clicked, then change the color to green. This is what I have im ...

Choose from a variety of video play options

Being new to javascript, I've successfully combined two functions that control video playback, but they seem to be conflicting with each other. The first function is designed to offer custom pause and play controls for the video // VIDEO CONTROLS STA ...

Adding two input values using jQuery

Here is the function compute() that I am working with: function compute() { if ($('input[name=type]:checked').val() != undefined) { var a = $('input[name=service_price]').val(); var b = $('input[name=modem_pric ...

Using the "this" keyword is required for an Angular Service-created function

Although this question leans more towards JavaScript than Angular, I encountered an issue while creating a service. The function call looked like this: // controller injects activityApi , then service function call is made var activities = activityApi.get ...

Angular JS Form's Pristine feature is malfunctioning when attempting to reset

I implemented a login form on my website. After submitting the form, I clear it and set it to Pristine mode. However, the error message still persists. Below is the code for my form: <form name="loginForm" ng-submit="loginForm.$valid && login( ...

Here is a way to prevent a null input value from being accepted in a JavaScript function

Hey there, I have a function that looks like this: class Fun { pem_Files_Checker_And_Adder_Server_Id_Adder(id , serverType , hostname) { //do something }; }; } In order for this function to work properly, I need to give it some values. For exam ...

Tips for implementing a guard feature using a modal window

I am looking to implement a dialog window with yes and no responses when clicking on a router link. If the user selects 'yes', I want to pass through the canActivate guard. The issue arises when returning to the same router with the guard in pla ...

Raphael and jQuery/JavaScript for user-selected array intersections

Hello everyone! This is my first time posting here, and I must say that I'm still quite new to JavaScript/jQuery/Raphael. Please forgive me if I make any mistakes or ask basic questions. :) I've been searching high and low for answers to my quer ...

The deleteCell function will not properly function when directly targeting selected table rows (trs)

I'm currently facing an issue while trying to dynamically access a specific tr element. Although I believe that the tr is being selected, when attempting to use the deleteCell method, it gives an error stating that the object does not have such a meth ...

Creating numerous bar graphs for each specific date

I have a dataset containing dates and corresponding information for each element. Despite trying various approaches, I am unable to create a barchart. Every solution I've attempted has been unsuccessful thus far. The dataset is structured as follows ...

Encountering a `ECONNREFUSED` error while attempting to dispatch an action in the

I have decided to convert my Nuxt application to SSR in order to utilize nuxtServerInit and asyncData. Below are the steps I followed during this conversion process. Removed ssr: false from nuxt.config.js Dispatched actions to initialize the store's ...

Request for /Account after Keycloak token request in Angular app

I have been working on an Angular and Keycloak project. I followed a tutorial that helped me integrate Keycloak into Angular, which can be found here: https://www.npmjs.com/package/keycloak-angular My public client is able to request a token, but when it ...

Sometimes, the `undefined` TypeError can unexpectedly pop up while making Ajax calls

Here is my issue with AJAX request and response: I have around 85 HTML pages that all use the same AJAX request. However, when working with these files, I sometimes encounter the following error. AJAX $(document).ready(function(){ localStorage.setIte ...

When utilizing a Service through UserManager, the User variable may become null

Utilizing Angular 7 along with the OIDC-Client library, I have constructed an AuthService that provides access to several UserManager methods. Interestingly, when I trigger the signInRedirectCallback function from the AuthService, the user object appears ...

An HTML form featuring various submit buttons for accomplishing different tasks

After searching extensively, I have come across solutions that are similar but not quite right for my specific situation. Here's what currently works for me: <script type="text/javascript"> function performTask1(a, b) { window.open('intern ...

By default, the HTML table will highlight the specific column based on the current month using either AngularJS or JavaScript upon loading

I am working with a table of 10 products and their monthly sales data. Using Angular JS, I am looking to highlight the entire column based on the current month and year. Additionally, we will also be incorporating future expected sales data into the table. ...

Troubleshooting Issue: XMLHttpRequest Incompatibility with Internet Explorer

I'm having an issue with the script below. It works fine on Firefox and Chrome but doesn't seem to work on IE. I've tried various solutions, including lowering the security settings on my browser, but it still won't work. function se ...