Updating a boolean value when the checkbox is selected

Hey there! I'm currently working on a project using Angular and have a collection of elements that can be checked, which you can check out here.

In terms of my business logic:

stateChange(event: any, illRecipe: Attendance){

    var state: State = {
        is_checked: event.checked,
        attandance: illRecipe
    };

    this.checkboxValues.push(state);

    console.log(this.checkboxValues);

   
}

Whenever the checkbox is clicked, this function triggers and adds the value to the array. Now, I'm wondering: How can I update the objects in the array? Is there a more efficient way to achieve this than updating the object directly? While I know that the state updates, I seem to get a new element in the array.

Check out the current values in the array here.

UPDATE

Here's what I'm attempting now:

stateChange(event: any, illRecipe: Attendance){

    var state: State = {
        is_checked: event.checked,
        attandance: illRecipe
    };

    console.log(state);

        this.checkboxValues.push(state);
        //push the object into array

        var isSameId = this.checkboxValues.filter( value => value.attandance.id == state.attandance.id)
        // filter to find checkboxes that are clicked multiple times

        if(isSameId.length >= 2){
            this.checkboxValues.forEach((checkBoxValue, checkboxIndex) =>{
                isSameId.forEach((sameValue, sameIndex) =>{
                    if(sameValue.attandance.id == checkBoxValue.attandance.id && isSameId.length > 1){
                        this.checkboxValues.splice(checkboxIndex, 1)
                    }
                })
            })
        }
        //trying to sort out the older entries with the same id
   
    console.log("checkboxValues",this.checkboxValues);
}

My aim is to eliminate duplicates in the checkboxValues array. I'm making progress, but there seems to be a small issue somewhere. For example, if I click one checkbox three times, then another one, and go back to the first checkbox, it behaves unexpectedly where the unchecked object appears and the recently pressed one disappears from the array.

Frontend Implementation:

 <div *ngFor="let ill of illAttendances">
                <div *ngIf="!ill.is_file_uploaded" class="box">
                    <div class="p-grid">
                        <div class="p-col-1">
                            <p-checkbox (onChange)="stateChange($event, ill)"></p-checkbox>
                        </div>
                        <div class="p-col">
                            <div *ngIf="ill.start != undefined && ill.end != undefined">
                                {{ ill.absence_type | titlecase }} von <b>{{ ill.start | date:'d MMMM y' }}</b> bis
                                <b>{{ ill.end | date:'d MMMM y' }}</b>
                            </div>

                            <div *ngIf="ill.one_day != null">
                                {{ ill.absence_type | titlecase }} am <b>{{ ill.one_day | date:'d MMMM y' }}</b>
                            </div>
                        </div>
                    </div>

                </div>
                <br>
            </div>

Answer №1

To determine the best solution, it would be helpful to see your HTML code. One suggestion is to use an Array of State (referred to as stateList) and connect the checkbox to an item in that array. By doing this, the stateList will track the checked state of the corresponding Attendance, eliminating the need for a separate list or handling the stateChange event.

If you provide the view code for the checkboxes, we can offer further assistance.

I recommend replicating the approach below using your own data type and structure, as it's more efficient than having two separate lists for one task.

In your component.ts file, initialize the array with Attendance:

export class AppComponent {
  stateList = [];

  ngOnInit() {
    this.stateList.push({ is_checked: false, attandence: { name: 'Att1' } });
    this.stateList.push({ is_checked: false, attandence: { name: 'Att2' } });
    this.stateList.push({ is_checked: false, attandence: { name: 'Att3' } });
  }
}

In your HTML:

<div *ngFor="let state of stateList">
  <label>
    <input type="checkbox" [(ngModel)]="state.is_checked"/>
    {{state.attandence.name}}
  </label>
</div>

Using this method, the stateList will accurately keep track of all checked items. For a demonstration, check out the working example on this page.

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

The introduction of an underscore alters the accessibility of a variable

When working in Angular, I encountered a scenario where I have two files. In the first file, I declared: private _test: BehaviorSubject<any> = new BehaviorSubject({}); And in the second file, I have the following code: test$: Observable<Object& ...

What is the best way to find the average time in Typescript?

I am dealing with an object that contains the following properties: numberOfReturns: number = 0; returns_explanations: string [] = []; departure_time: string = ''; arrival_time: string = ''; The departure_time property hold ...

Angular displays RouterLink as regular text

I am currently learning Angular and encountering an issue with the routerLink attribute in my <a> tag. When I add the routerLink, it changes to text and becomes unclickable. Can anyone help me identify what is causing this problem? Here is a snippet ...

Transition from using ReactDOM.render in favor of asynchronous callback to utilize createRoot()

Is there a React 18 equivalent of this code available? How does it handle the asynchronous part? ReactDOM.render(chart, container, async () => { //code that styles some chart cells and adds cells to a worksheet via exceljs }) ...

Leveraging global attributes beyond Vue components - Vue 3

I have created custom service instances in main.ts app.config.globalProperties.$service1 = new Service1(); app.config.globalProperties.$service2 = new Service2(); While I can use these instances inside Vue components, I also want to be able to utilize the ...

Leveraging LESS in an Angular2 component

Currently, I am attempting to integrate LESS with angular2. To do so, I have imported the less.js file in my index.html and I am using the following command within the component: less.modifyVars({ '@currentTheme-bar': '@quot ...

An unusual error occurred stating that the `forEach` property does not exist on the given type

I am working on a chess game and encountering some Typescript errors that I'm struggling to comprehend. The issue arises in the following class method: clickEvent (e: MouseEvent): void { const coordinates: ClientRect = this.chessBoard.getBounding ...

The 'target' property is not found on the type 'KeyboardEventHandler<HTMLInputElement>'

My Visual Studio Code is giving me an error in my onKeyUp function when I try to access the input target and retrieve its value. import React from 'react'; import styles from './styles.module.scss'; export function Step3() { ...

When it comes to TypeScript, it feels like my interface can accept anything I throw at it, and it struggles to grasp how I've implemented and imported redux-toolkit and styled components

My Current Struggle: Errors in Typescript are occurring seemingly at random. The interface in my index.tsx file doesn't align with the object it should describe, yet no red flags are raised. On top of that: An error pops up when attempting to import ...

Error: Unable to bind 'datasets' as it is not recognized as a valid property of 'base-chart' in ng2-charts

Current Versions: Cordova: 6.3.1, Gulp CLI: 1.2.2, Ionic framework: 2.0.0-rc.0, Ionic CLI Version: 2.1.0 In my Ionic2 application, I have integrated the ng2-charts library. When importing, be sure to use import {ChartsModule} from "ng2-charts/components/ ...

The service does not fall within the 'rootDir' directory in the Angular secondary module

Encountering an error while compiling an Angular library related to the rootDir of sub libraries library/services/src/public-api.ts:31:15 - error TS6059: File 'C:/libname/library/services/src/orders/orders.service.ts' is not under 'rootDir& ...

Having trouble retrieving documents from a nested collection in Firebase

I am attempting to retrieve all documents from Firebase that are based on a query. Here is my current firebase structure: https://i.stack.imgur.com/tXrX8.png Even though I have two documents inside the "ListaFavorite" collection, when I check using empty ...

Icon for closing Mui Snackbar

I am facing an issue with my notification component that uses the mui snackbar to display alerts. I want to display multiple notifications stacked vertically, but when I try to close one notification using the "Close" icon, it ends up closing both that o ...

Instructions on retrieving keyboard input values from Angular's Material Datepicker using Reactive Forms

Currently, I am using Angular along with material datepicker within Reactive Forms and moment's MomentDateModule. My concern lies in extracting the value that a user types into the form via keyboard input. If you wish to see an example of this scenar ...

Guide on incorporating a YouTube iframe in React with Typescript

It appears that Typescript is posing some challenges for me in this scenario. Here's the code snippet I am trying to include: <iframe width="560" height="315" src="https://www.youtube.com/embed/BLAH?showinfo=0" frameBorder="0" ...

How do I determine if a child component is in a dirty state within CanDeactivateGuard when dealing with multiple form tags?

Currently, I am utilizing a template driven form within my project. The parent component that I am working on is as follows: parent.component.html <tab> <form> <input></input> <button></button> </form ...

The incredible power of the MongoDB $inc field

I am facing a challenge in writing a function that accepts a record id, an action (inc or dec), and a field name as a string to be incremented (can be 'likes', 'subs' or any other). The issue is that I am unable to find a way to replac ...

Transferring a PDF document to a server via a POST request

I have implemented a PDF upload section for users on my website and I want to send the uploaded file to an S3 bucket through a micro-service that I have developed. However, when I try to send the file from the front-end, it seems to be coming through empty ...

When a 404 error is thrown in the route handlers of a Next.js app, it fails to display the corresponding 404 page

I am encountering an issue with my route handler in Next.js: export async function GET(_: Request, { params: { statusId } }: Params) { const tweetResponse = await queryClient< Tweet & Pick<User, "name" | "userImage" | &q ...

Dealing with inconsistent wait problems in Angular applications with Protractor and Jasmine

In my current project, I am using Angular for building the application along with Protractor and Jasmine for e2e tests. However, we have been experiencing inconsistent test script failures during execution. To tackle this issue, we tried setting ignore.s ...