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!