How to automatically set a checkbox as checked in an edit component using Angular 5 when the corresponding array object has a checked=true attribute

When retrieving an array from a data object via API service call, I am attaching a checked attribute to ensure that checkboxes are selected in the component's ngOnInit().

My objective is to have only the checkboxes related to the data retrieved from the service call be selected in a master checkbox list.

Various methods have been attempted, such as for loops and .forEach() on the array.

this.filterService.GetTierContent(this.config.id, "MCC").subscribe(data 
     => {
  data.forEach(i => this.selectedMcc.push({ type: "MCC", data: i.data, 
  checked: true }));    
  });

for(var i=0; i < this.selectedMcc.length; i++){
var index = this.selectedMcc.findIndex(i => i.data == i);
  if(this.selectedMcc[index].checked === true) {
    this.chk1 = true;
  }    
  else {
    this.chk1 = false;
  }
}  


  <div *ngFor="let a of apparel; let i = index"> 
            <mat-checkbox value="{{a.id}}" [(ngModel)] ="chk1" 
   (change)="onChecked(a, $event)">
                {{a.mccCode}}
            </mat-checkbox>
        </div> 

Expected outcome:

[(ngModel)] will store either a true or false value based on the looping process. Only data arrays returned from the service should be pre-checked by default upon component load.

Current issue: checking one box applies the selection to all checkboxes.

Answer №1

Do you think this strategy could work?:

// Start by resetting all checked states to false in the apparel-list
this.apparel.forEach(element => {
    element.checked = false;
});

// Next, iterate through the new list
this.selectedMcc.forEach( element => {
    // If an element is checked, mark its corresponding item in the apparel-list as checked
    if (el.checked === true) {
        this.apparel.filter(item => item.id === element.id)[0].checked = true;
    }
});

// This should result in only the selected items from the incoming list being marked
<div *ngFor="let a of apparel; let i = index"> 
    <mat-checkbox 
        value="{{a.id}}" 
        [(ngModel)]="a.checked" // link the checked status of the apparel-list item
        (change)="onChecked(a, $event)">
        {{a.mccCode}}
    </mat-checkbox>
</div> 

Note: This assumes that elements in the apparel-list have a checked field.

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

Error in compiling caused by an absent property on JSX element

While working with material-ui, I came across a Slider element: <Slider ... sliderStyle={{}} ...> An error message popped up: error TS2339: Property 'sliderStyle' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttri ...

Compiling a TypeScript project to generate the correct index.js file is currently not successfully completed

Looking to set up the TypeScript project here. The steps are: git clone https://github.com/simpleledger/BitcoinFilesJS.git test/ cd test npm i tsc # or npx tsc The resulting index.js is shown below: "use strict"; var __createBinding = (this & ...

The activation of Angular 2 pipe

I currently have a variety of models in my collection. When it comes to using pipes in the template, I often run into issues. <div class="card-panel" *ngFor="let card of cards | sortByType"> <card-view [card]="card" [autoupdate]="true">< ...

Show detailed information in a table cell containing various arrays using AngularJS

After integrating d3.js into my code, I now have an array with key-value pairs. Each team is assigned a key and its corresponding cost is the value. When I check the console log, it looks like this: Console.log for key and value Rate for current month [{ ...

I am encountering issues with the ng-bootstrap drop down menu not functioning properly when used in conjunction with *ng

The dropdown menu is designed to dynamically populate a selection of languages. I attempted to use ngFor to achieve this, but only the first item in the list appears in the dropdown menu. <nav class ="navbar navbar-light bg-light fixed-top"> &l ...

Insert a triangle shape at the bottom of the material design tab with the class mat-ink-bar

I'm trying to update the appearance of the mat-ink-bar in the Angular material tab. My goal is to achieve a design similar to this: Jsfiddle example The issue I'm facing is that the mat-ink-bar is already positioned as absolute, making it diffi ...

Issue with retrieving properties in Angular template due to undefined values in HTML

As a newbie to Angular, I am dedicated to improving my skills in the framework. In my project, I am utilizing three essential files: a service (Studentservice.ts) that emits an observable through the ShowBeerDetails method, and then I subscribe to this ob ...

Error due to PlatformLocation's location dependency issue

My AppComponent relies on Location (from angular2/router) as a dependency. Within the AppComponent, I am using Location.path(). However, when running my Jasmine test, I encountered an error. Can you help me identify the issue with my Jasmine test and guide ...

How can I prevent the installation of my Ionic 2 application on devices that have been rooted or jailbroken?

I am currently working on a project involving an Ionic 2 and Angular 2 application. I need to implement a feature that checks whether the device is rooted (in the case of Android) or jailbroken (in the case of iOS). I have experimented with various packag ...

Introducing an extra 'pipe' in rxjs angular may result in generating errors

Encountering an unusual issue with Angular. The following code functions correctly: this.form.valueChanges .pipe( startWith(this.form.value), pairwise(), tap(() => console.log('aa')) ...

Customizing hover color with tailwind CSS

How can I change the color of an icon on mouseover using Tailwind CSS? I have tried to go from this https://i.sstatic.net/ObW6C.png to this https://i.sstatic.net/Tagp3.png, but it's not working. .btn { @apply agt-h-10 agt-w-10 agt-bg-zinc-100 agt- ...

Exploring Angular 4: A deep dive into routing and ensuring responsiveness

I set up an ubuntu server on AWS and most things are running smoothly, but there are a couple of issues that have me stumped. When visiting my web app, you can only interact with the buttons in the menu. Trying to access a link like 'mypage/items&ap ...

Refreshing user information on Ionic platform

Hello there, I am seeking assistance on updating user data in Angular and Ionic. I have managed to retrieve the user ID from local storage and create a method to store the new user data. However, I'm struggling with updating the user with this new inf ...

Problem: Unable to locate the TypeScript declaration file

I am facing an issue with my TypeScript configuration. I have two files in /src/models/: User.ts and User.d.ts. In User.ts, I am building a class and trying to use an interface declaration for an object defined in User.d.ts. However, User.ts is unable to a ...

Warning: NgOptimizedImage Optimization_NOTICE

Exploring the latest features of angular 15 to enhance image performance led me to encounter this cautionary message. `The NgOptimizedImage directive (used on an <img> element with `ngSrc="/assets/fascinating.png") has detected that the ori ...

Object data is not being received by the defaultValue in React Hook Form

I am currently utilizing React Hook Form to facilitate the process of editing/updating data. I retrieve my data from zustand with a value type of any, and then proceed to save it as the defaultValue in React Hook Form. However, when attempting to acquire v ...

Encountered an error: Template parsing issues arose when integrating kendo-angular-scheduler into the app.module

I integrated the kendo-angular-scheduler into my Angular app using the following command: ng add @progress/kendo-angular-scheduler Although I have installed this module, I have not utilized it in my project yet. After compiling the code, an error message ...

The correct procedure for refreshing a page in Angular 8

Note: I found some code snippets online but, after testing them out, I have doubts about their reliability due to inconsistencies. In my script, I have developed two utility functions - one for moving to the parent node and another for reloading the curre ...

How can one correctly cast or convert an array of objects to the interface that extends the objects' parent interface in Typescript?

Question: How can I optimize the usage of method sendItemIdsOverBroadcastChannel to reduce message size? interface IItemId { id: number; classId: number; } interface IItem extends IItemId { longString: string; anotherLongString: string } inte ...

I encountered a TypeScript error in React Native when attempting to use "className" with TypeScript

Although I've been using React for a while, React Native is new to me. I recently started using tailwind with import { View, Text } from "react-native"; import React from "react"; export default function Navigation() { return ...