The issue with Angular's Array.push method arises when only the last object in the array is being pushed after a mat-checkbox

I am currently working with two components called item-list and item. The item-list component is responsible for displaying a list of items with checkboxes. I have been facing an issue where the Array that stores the checked items only retains the last item when logged.

Below is the code snippet that I have tried:

item-list.component.html

<div>
  <mat-form-field appearance="outline">
  <input matInput placeholder="Add a Task" (keyup.enter)="addTask()"autocomplete="off" [formControl]="nameControl"/>
  </mat-form-field>
</div>

<app-item
  [value]="value"
  *ngFor="let value of data; index as index"
  >
</app-item>

item.component.html

<div class="listContainer">
  <div class="checkContainer">
  <mat-checkbox color="secondary" [(ngModel)]="IsChecked" (change)="onChange($event)"> 
  </mat-checkbox>
  </div>
</div>

<div class="displayTask">
 <div class="displayvalue" [ngClass]="{ 'line-through': value.task }">
  {{ value.task | uppercase }}
 </div>
</div>

item.component.Ts

import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';

@Component({
  selector: 'app-item',
  templateUrl: './item.component.html',
  styleUrls: ['./item.component.scss'],
})

export class ItemComponent implements OnInit {

  @Input()
  value: any;

  IsChecked: boolean;
  public ArrayChecked: any[] = [];

  constructor() {
    this.IsChecked = false;
  }

  ngOnInit(): void {}

  onChange($event: any) {
     if ($event.checked) {
       this.ArrayChecked.push(this.value.task);

       console.log('the task is added', this.ArrayChecked);
     } 
     else console.log('the task is removed');
  }
}

In the code above for the item component, I attempted to add the checked items to an array named 'ArrayChecked' within the onChange() function. However, the output only contains the last checked item instead of all the checked items. I need assistance in resolving this issue and ensuring that all checked items are stored in the 'ArrayChecked[]'. Your help is greatly appreciated. Thank you!

Answer №1

The issue at hand is that the ArrayChecked variable is being initialized in each individual item component, causing each component to only store values in its own ArrayChecked. As a result, only the value of the last checked checkbox gets logged.

To resolve this, it is recommended to initialize the ArrayChecked variable in the higher-level item-list component instead of within each item component. Subsequently, the item component should trigger an event when the checkbox value changes along with the task associated with the item. This event can then be listened for in the item-list component, allowing the task to be pushed to the shared ArrayChecked.

item.component.ts

import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';

@Component({
  selector: 'app-item',
  templateUrl: './item.component.html',
  styleUrls: ['./item.component.scss'],
})

export class ItemComponent implements OnInit {

  @Input()
  value: any;

  // Emitted when the task is checked
  @Output()
  checkTask = new EventEmitter<any>;

  IsChecked: boolean;

  constructor() {
    this.IsChecked = false;
  }

  ngOnInit(): void {}

  onChange($event: any) {
     if ($event.checked) {
       // Emit the checkTask event instead of directly pushing to the array
       this.checkTask.emit(this.value.task);

       console.log('the task is added', this.ArrayChecked);
     } 
     else console.log('the task is removed');
  }
}

item-list.component.html

<app-item
  [value]="value"
  (checkTask)="addCheckedTask($event)"
  *ngFor="let value of data; index as index"
  >
</app-item>

item-list.component.ts

addCheckedTask($event: any): void {
  this.ArrayChecked.push($event);
}

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 steps do I need to take in order to develop a custom component for FormControls?

Trying to create a form with a custom component for controls, I encountered an issue. Despite including the new component in the parent form that already has a formGroup, Angular throws an error. The error I faced is: Error: formControlName must be use ...

Differentiating response.data typing on the front end in Typescript depending on the request's success status

Consider this scenario: A secure API authentication route that I am not allowed to access for viewing or editing the code returns interface AuthSuccess { token: string user: object } on response.data if the email and password provided are correct, but ...

Using electron cookies in Angular involves integrating Electron's native cookie functionality into an

I am currently dealing with electron and looking to implement cookies conditionally in my project. If the application is built using electron, I want to utilize Electron Cookies; otherwise, I plan to use Angular Cookies. However, I'm encountering diff ...

Changing the data type of a column in an Excel file from XLSX to

I am currently working with the XLSX npm package and attempting to download a sample Excel file, add some data to it, and then upload it back. The fields in the file include MOBILE NUMBER, DATE, TIME, and NAME. When I upload the file, the values for the DA ...

What is preventing the combination of brand enums in Typescript 3?

Utilizing brand enums for nominal typing in TypeScript 3 has been a challenge for me. The code snippet below demonstrates the issue: export enum WidgetIdBrand {} export type WidgetId = WidgetIdBrand & string; const id:WidgetId = '123' as Wi ...

A guide to effectively utilizing a TypeScript cast in JSX/TSX components

When trying to cast TypeScript in a .tsx file, the compiler automatically interprets it as JSX. For example: (<HtmlInputElement> event.target).value You will receive an error message stating that: JSX element type 'HtmlInputElement' is ...

Is there a way to retrieve the ReturnType<T> for all methods within a class, even if the ReturnType<T> and its usage appear to be static?

After extensively reviewing the documentation on typescript at https://www.typescriptlang.org/docs/handbook/utility-types.html#returntypet, I have come across two instances of ReturnType<T> mentioned. However, these instances appear to be statically ...

Executing Promises in TypeScript Sequentially

I have a collection of doc objects and I need to send an API request for each doc id in the list, executing the requests in a sequential manner. In my Typescript code, I am using Promise.all and Promise.allSelected to achieve this. [ { "doc_id&q ...

Exploring the capabilities of automation testing with charts.js and the latest version of Angular

While working on my testing automation for charts.js, I utilized the ngContext object to retrieve data with this code snippet: document.getElementsByTagName('chart-dataset')[0].__ngContext__. However, since upgrading to angular 14, it seems that ...

npm encounters difficulty in reverting to a previous version of the node package (angular-cli)

Encountering some bugs in the current version of the node package angular-cli led me to decide to revert back to a previous version, specifically 1.0.0-beta.28.3. The main puzzle I'm faced with now is figuring out the necessary steps to rollback to a ...

Troubles in transitioning a local project from Angular 2 to Angular 4 using Angular-cli

I have been working on updating an angular-cli/angular 2 project to Angular 4. I successfully updated the package.json file with all the necessary Angular 4 modules, but encountered an issue when running the application. Upon running the app, I received th ...

Encountering an issue with extending the MUI color palette, receiving a "reading 'dark'" error due to properties of undefined

Encountering an issue when trying to expand the MUI color palette—getting this error instead: Error: Cannot read properties of undefined (reading 'dark') Take a look at my theme.ts file below: const theme = createTheme({ palette: { pri ...

Sending a POST request that is attempting to insert empty values into an MS SQL database

Here is the code I am working with - onSubmit(){ var headers = new Headers(); headers.append('Content-Type', 'application/x-www-form-urlencoded'); let postParams = { firstName : this.firstName, lastName : this.lastNa ...

Ensure that the dynamically inserted <title> tag remains intact in Angular even when the page is re

Can the dynamic title tag be preserved when the page is refreshed? When I refresh the page, the title tag reverts back to the original one specified in the index.html temporarily before switching back to the dynamically added one. I want the title tag to ...

The Bootstrap carousel is experiencing compatibility issues with Angular 7 and is currently not functioning properly

I'm currently using the bootstrap multi carousel, and it works perfectly without a loop. However, when I try to implement it dynamically using an ngFor loop, it doesn't function as expected. Instead of sliding with multiple images, it just displa ...

What is the best way to add an item to an array with distinct properties?

I am currently working on creating an array with different properties for each day of the week. Here is what I have so far: const [fullData, setFullData] = useState([{index:-1,exercise:''}]) My goal is to allow users to choose exercises for a sp ...

Angular routing functions flawlessly on Chrome Mac but encounters issues on Chrome iOS

Encountering a strange issue. My routing is properly configured and has been verified multiple times. Oddly enough, page1, page3, and page5 are functioning correctly, while page2, page4, and page6 fail to redirect as expected. Upon clicking the redirect ...

Angular 8 experiencing unexpected collision issues

Currently, I am utilizing Angular 8 with "typescript": "~3.5.3". My objective is to handle the undefined collision in my code. const { testLocation } = this.ngr.getState(); this.step2 = testLocation && testLocation.step2 ? testLocat ...

Sorting and dividing an Array using Angular

Forgive me in advance if this sounds like a naive question, as Angular and Typescript are not my strong suits. I am assisting a friend with an issue that I can't seem to overcome. I have an array of players that includes details such as first name an ...

Loader for dynamically loading tabs in Angular 2

I am looking to develop a dynamic tabs loader using Angular 2 material with specific syntax support. <generic-tabs [tabs]="tabs" tabVisibleField="name"> <test-cmp [tabContent] testData="hello"></test-cmp> ...