Tips for setting the checkbox and select box to be automatically checked based on specific column values in Angular 7

My table is populated with values from a JSON file that contains various columns. Clicking the edit button opens a box where checkbox values are sourced from another JSON file (statusdata). The issue arises when the checkboxes need to be checked based on the status column value of the clicked row. To close the box, simply click on the close link. You can find the code below: https://stackblitz.com/edit/angular-zqswrw

app.component.html

<table class="table border">
    <thead>
        <tr>
            <ng-container *ngFor="let column of columns; let i = index">
                <th>{{ column }}</th>
            </ng-container>
        </tr>
    </thead>
    <tbody>
        <tr *ngFor="let row of groups;let i = index">
            <td>{{row.name}}</td>
            <td>{{row.items}}</td>
            <td >
                <span class="status" *ngFor="let item of row.Status ;let j = index">
                    {{item.name}}
                   </span> <span  *ngIf = "i == hoverIndex" class="hover-details"></span>
           </td>
            <td style="cursor:pointer;" (click)="edit(row);">Edit</td>
        </tr>
  </tbody>
</table>
<div style="border: 1px solid #000;
    padding: 10px;
    display: flex;
    width: 100%;
    margin-top: 1%;" *ngIf="block">

Status-checkbox:<div style="float:left" *ngFor="let status of statusdata">
 <input type="checkbox" [checked]="" value="status.id" />{{status.name}}
</div>

<div (click)="close();" style="cursor:pointer;float:right;margin-left:10%;">close</div>
</div>

app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  dotsh:any;
    hoverIndex:number = -1;
    groups:any;
    test:any;
    statusdata:any;
    block:any;
    closeit:any;
  onHover(i:number){
 this.hoverIndex = i;
}
     columns = ["name", "Items","status","Action"];


  edit(dataItem){
    console.log(dataItem.status);
    this.block = true;  
  }
  ngOnInit() {
      this.closeit = true;
      this.block = false;
      this.test = false;
      this.groups=[{"id":1,"name":"pencils","items":"red pencil","Status":[{"id":1,"name":"green"},{"id":2,"name":"red"},{"id":3,"name":"yellow"}],"loc":[{"id":1,"name":"loc 1"},{"id":2,"name":"loc 2"},{"id":3,"name":"loc 3"}]},{"id":2,"name":"rubbers","items":"big rubber","Status":[{"id":1,"name":"green"},{"id":2,"name":"red"}],"loc":[{"id":1,"name":"loc 2"},{"id":2,"name":"loc 3"}]},{"id":3,"name":"rubbers1","items":"big rubber1","Status":[{"id":1,"name":"green"}],"loc":[{"id":1,"name":"loc 2"},{"id":2,"name":"loc 3"}]}];
      this.statusdata = [{"id":1,"name":"green"},{"id":2,"name":"red"},{"id":3,"name":"yellow"}];




} 
close(){
    this.block = false;
}
}

Answer №1

To effectively manage the checked state of checkboxes, consider adding a variable to your array that will store the checkbox status. The code snippet below demonstrates how you can implement this solution:

app.component.html

Status-checkbox:<div style="float:left" *ngFor="let status of statusdata">
 <input type="checkbox" [checked]="status.checked" value="status.id" />{{status.name}}
</div>

app.component.ts

  edit(dataItem){
      console.log(dataItem.status);
    this.block = true;  

    this.statusdata = this.statusdata.map((item)=>{
      item.checked= false;
        for(var d=0;d<dataItem.Status.length;d++){
          if(item.id==dataItem.Status[d].id){
            item.checked = true;
            break;
          }
        }
      return item;
    });
  }

Answer №2

If you want to not only display whether something is checked but also be able to change it, you should use [(ngModel)] instead of [checked]. The code by Narayanan works well, but it can be made more straightforward.

Additionally, in order to track the changes, we need an auxiliary variable called "itemEdit". The edit and close functions can be simplified as follows:

itemEdit:any //<--declare an auxiliary variable to store the item being edited

edit(dataItem) {
    this.itemEdit = dataItem; //<--save a "reference" of the data we are editing 
    this.statusdata.forEach(x => {  //for each element in "statusdata"
      x.checked = dataItem.Status.find(data => data.id == x.id); //set the "checked" value
    });
    this.block = true;
}

close() {
    //our save "reference", the Status was
    this.itemEdit.Status = this.statusdata
      .filter(x => x.checked)  //get only the values of statusdata.checked
      .map((d: any) => {  //but only want object with id and name properties
        return { id: d.id, name: d.name };
      });
    this.block = false;
}

The .html file uses [(ngModel)]

Status-checkbox:
 <div style="float:left" *ngFor="let status of statusdata">
    <input type="checkbox" [(ngModel)]="status.checked" 
            value="status.id" />
    {{status.name}}
</div>

Your forked StackBlitz

Update: If we have a select input instead of checkboxes, the technique is similar.

You need a variable statusEdit and use [(ngModel)]

Status-checkbox:<div style="float:left">
        <select [(ngModel)]="statusEdit" >
   <option *ngFor="let status of statusdata"  [value]="status.id">{{status.name}}</option>
 </select>

The edit and close functions would then look like this (note that we are now modifying dataItem.Status[0] since Status is an array with one element):

  edit(dataItem) {
    this.itemEdit = dataItem;
    this.statusEdit = dataItem.Status[0].id;
    this.block = true;
}
close() {
    this.itemEdit.Status[0] = {
      ...this.statusdata.find(x => x.id == this.statusEdit)
    };
    this.block = false;
}

Once again, feel free to check out your updated link on StackBlitz

Answer №3

After reviewing your stackblitz example and the instructions provided, I was able to resolve the issue with the selected checkbox not being checked.

Firstly, you need to update the parameters of your edit function with the following code:

<tr *ngFor="let row of groups; let i = index">
    <td>{{row.name}}</td>
    <td>{{row.items}}</td>
    <td>
        <span class="status" *ngFor="let item of row.Status; let j = index">
            {{item.name}}
        </span> <span  *ngIf="i == hoverIndex" class="hover-details"></span>
    </td>
    <td style="cursor:pointer;" (click)="edit(row.Status);">Edit</td>
</tr>

Create a variable at the top of the page:

selected_item_id = 0;

Make some updates to your edit function as follows:

edit(dataItem){
    this.block = true;  
    this.selected_item_id = dataItem[0].id;
}

Lastly, update the options in the select box with the following code:

<select>
    <option *ngFor="let status of statusdata" [selected]="status.id == selected_item_id">{{status.name}} </option>
</select>

I believe everything has been covered now.

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

Displaying an image on canvas while showing a loading progress bar

I'm attempting to utilize this function to load an image into my canvas: function handleImage(e) { var reader = new FileReader(); reader.onload = function (event) { var img = new Image(); // img.onprogress = function (e) { ...

"When implementing an Ajax autorefresh feature, ensure you pass the necessary variables consistently to update the content. Don't overlook

My chat box consists of two frames... The first frame displays all the usernames, while the second frame shows the full chat when a user is clicked from the first frame. I need to reload the second frame every time to check for new messages from the send ...

Challenges arise when incorporating interfaces within a class structure

I created two interfaces outside of a class and then proceeded to implement them. However, when I tried to assign them to private properties of the class, something went wrong and I'm unable to pinpoint the issue. Can anyone offer assistance with thi ...

Guide on triggering background notifications to display in the foreground of an Angular Firebase application using Angular 9 webapp

I've been using Angular Firebase for push notifications and everything is going smoothly with foreground messages. However, I encountered an issue when trying to handle background messages by adding a 'setBackgroundMessageHandler' call in my ...

Display the list items when the page first loads

I currently have this code snippet: <nav> <ul class="sel"> <li> <a href="#LINK1" data-title="A">A</a> </li> <li> <a href ...

When using the Android platform, the webpage may not be loading correctly and certain links may be unresponsive in the webview

While viewing my webpage on Google Chrome in my Android phone, the website loads perfectly and functions as expected. However, when I try to load the same webpage in Webview, the site does not load correctly, especially the jQuery content. Additionally, no ...

Problem Encountered with Jquery Validation for Name Field (Restriction to Alphabetic

I am struggling to validate a name format using a predefined jQuery validation tool. My intention is for the name field to accept only characters, but even with the correct regex pattern, it still allows numbers to be entered. The specific script I am us ...

Why is NgOnChanges not Triggering Following HTTP Request?

There seems to be an issue with the ngonchanges not triggering in my Angular component. Here is the code snippet of the component: @Component({ selector: 'conversation-detail', templateUrl: './conversation-detail.component.html&apo ...

"I am experiencing an issue with a tick symbol not displaying correctly in my

I have created an XSLT file where I have implemented the following code snippet. To display a tick symbol in front of "Hello World," I have used ✓. The purpose of this XSLT is to parse an XML response and convert it into HTML format. <td colspan ...

JavaScript and HTML: Creating Single Page Applications and Managing asynchrony cancellation

In the midst of developing a one-page application, I am encountering challenges typical to this kind of project for the first time. On each page, there are certain asynchronous tasks that may be initiated and could potentially take up to 30 seconds to com ...

Elevate Your Flipclock.js

I am currently working on a website that utilizes flipclock.js, but I am facing some challenges in enlarging it to occupy more space on the page. Is there anyone who knows how to upscale or increase its size? ...

Combining SPA and ASP.NET MVC Routing techniques

In my current project, I'm handling a combination of Angular 2 and ASP.NET Core 2 (razor) routing. I am trying to figure out a way to switch from Angular routing to razor pages. I attempted to catch all unknown routes with Angular routing and reload t ...

Adding a document to Angular

Are you able to add a file in Angular? I've successfully made an HTML/CSS/Bootstrap website, but struggling to replicate it in Angular. Is there a way to integrate the existing site into Angular? If so, how can this be done? I attempted to insert the ...

TS2403 error occurs when an unexported variable with an identical name is utilized in multiple files

As a newbie in the world of TypeScript, I am venturing into creating a backend with Node.js (or should I say Node.ts?). Currently, I am in the early stages of setting up my server and exploring the fundamentals. My setup includes ts-node version 8.6.2 and ...

No data found in req.query object in ExpressJS

When I use http.post to send data from Angular to NodeJS, the req.query always comes back empty for me. Here is my server.js setup: const express = require('express'); const cors = require('cors'); const bodyParser = require('body ...

Angular - Enhance ngFor index while filtering

I am currently working with a list that utilizes an *ngFor loop in the template: <li *ngFor="let product of products | filterProducts: selectedFilter; index as productId"> <a [routerLink]="['/product', productId]"> {{produc ...

Exploring Angular 2 on Apache: A Guide to Optimizing for Search Engine

After creating a basic Angular 2 app and hosting it on an Apache server, I'm unsure if search engines will crawl my site. I read that the site must be rendered server side but couldn't find more information about it online. ...

Create code with a form button and showcase the produced code on the webpage

I have created two files: code_generator.html, which takes input in the form of an image URL and landing URL. When I click on the submit button, it calls code_created.php. <html> <head> </head> <body> <form a ...

What is the best way to emphasize a div depending on a query outcome?

A new application is in the works for a gaming project. This app is designed to display the location of a specific monster, utilizing a database containing information about monsters and their corresponding maps. Currently, the application functions almos ...

Stop the CSS animation when the cursor leaves and resume from the same position

I'm currently working on implementing a SVG path animation that activates on hover and reverses when the mouse is moved away. How can I pause the animation if the mouse moves out before the initial animation completes, and then reverse it from that p ...