Transform the entire row's color when a checkbox is selected in Angular 4

Is there a way to make an entire row clickable and change the color of the row when clicking on a checkbox?

Below is my HTML file:

<section class="others">
<div class="sub-header">Others</div>
<p class="text-center" *ngIf="otherTests.length === 0">No Tests Available</p>
<app-custom-accordion [closeOthers]="true">
<ngb-panel [disabled]="true" *ngFor="let testPanel of otherTests" id=". {{testPanel.Id}}" [title]="testPanel.Name">
  <ng-template ngbPanelTitle>
    <div class="action-items">
      <span class="material-icons fav" [class.favorited]="testPanel.Favorite" (click)="onFavoriteClick(testPanel)"></span>
      <span class="icon-set" [ngClass]="{'same-day-2x': isSameDay(testPanel.Code), 'next-day-2x': isNextDay(testPanel.Code)}"></span>
      <label class="custom-control custom-checkbox">
        <input type="checkbox" class="custom-control-input" [name]="testPanel.Id + '-' + testPanel.Moniker" [ngModel]="panelIds.indexOf(testPanel.Id) > -1"
        (ngModelChange)="onPanelCheckboxUpdate($event, testPanel)" [id]="testPanel.Id + '-' + testPanel.Moniker">
        <span class="custom-control-indicator"></span>
      </label>
    </div>
  </ng-template>
</ngb-panel>

Beneath is my TS file for handling checkbox changes:

onPanelCheckboxUpdate($event: boolean, panel: TestOrderPanel) {
let testPanelIds = panel.Tests.map(test => test.Id);
// Remove any duplicates
this.panelIds = this.panelIds.filter(
  panelId => panel.Id !== panelId && testPanelIds.indexOf(panelId) === -1
);
this.selectedPanels = this.selectedPanels.filter(
  selectedPanel =>
    panel.Id !== selectedPanel.Id &&
    testPanelIds.indexOf(selectedPanel.Id) === -1
);

if ($event) {
  this.panelIds.push(panel.Id);
  this.selectedPanels.push(panel);
   }
  this.updateSession();
}

This is the app-custom-accordion component:

 <div class="card">
 <ng-template ngFor let-panel [ngForOf]="panels">
<div role="tab" id="{{panel.id}}-header" [class]="'card-header ' + 
 (panel.type ? 'card-' + panel.type: type ? 'card-' + type : '')"
  [class.active]="isOpen(panel.id)">
  <a href (click)="!!toggle(panel.id)" [attr.tabindex]=" . 
 (panel.disabled 
  ? '-1' : null)" [attr.aria-expanded]="isOpen(panel.id)"
    [attr.aria-controls]="(isOpen(panel.id) ? panel.id : null)" 
 [attr.aria-disabled]="panel.disabled">{{panel.title}}</a>
  <ng-template [ngTemplateOutlet]="panel.titleTpl?.templateRef"></ng- 
  template>
  <!-- expansion arrows -->
  <div *ngIf="arrowExpand" (click)="toggle(panel.id)" [attr.aria- 
  expanded]="isOpen(panel.id)">
    <span class="material-icons expand"></span>
  </div>

 </div>
 <div id="{{panel.id}}" role="tabpanel" [attr.aria-labelledby]="panel.id + '-header'" class="card-block" *ngIf="isOpen(panel.id) && panel.contentTpl">
  <ng-template [ngTemplateOutlet]="panel.contentTpl?.templateRef"></ng-template>
      </div>
    </ng-template>
  </div>

How can I change the row color when clicking on a checkbox? I want the whole row to be dark when the checkbox is selected and go back to its previous color (white) when unchecked. Can anyone assist with this? Thank you!

Answer №1

If you are searching for a way to style elements based on the state of a checkbox in Angular, you can make use of Angular's directives like ngStyle and NgClass. Simply store the checkbox state in a variable accessible to the relevant rows, and then apply the desired styling using code similar to the examples below:

<some-element [ngClass]="{'class-wanted-when-checked' : checkboxIsChecked}">...</some-element>

Alternatively, you could use this approach:

<some-element [ngStyle]="{'background-color': checkboxIsChecked ? "blue" : "white"}">...</some-element>

Answer №2

I completely agree with @Tyler's point of view. However, instead of coloring all rows, we can color specific rows by following these steps (Special thanks to @Tyler for sharing his code snippet):

        <tr *ngFor="let item of items" [ngStyle]="{'background-color': item.completed ? 'lightblue' : 'white'}">
            <td>
                <input type="checkbox" (change)="item.completed = !item.completed">
                
            </td>
        </tr>  

In this code snippet, the variable task.completed is used as a boolean flag.

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

Utilizing a confined environment to retrieve a value in order to conceal certain buttons

My goal is to utilize an isolated scope in order to access the hideButtons property within the directives named todo-cardui and todo-formui: app.directive("todoFormui",function(TodoService){ var dirDefObj = { restrict:'E', t ...

What is the best way to import the L module from the "leaflet" library in Next.js?

Implementing Leaflet into my Next.js development posed a challenge as it did not support server side rendering (SSR). To address this, I had to import the library with SSR disabled using the following approach: import React, {Component} from "react&qu ...

Header Blocks that are Fixed While Scrolling in fullPage.js Sections Using the "scrollOverflow: true" Feature

I am experiencing an issue where a fixed header on my website prevents scrolling through sections when hovering, specifically when the setting scrollOverflow: true is enabled. However, everything works fine and scrolling through all sections is possible w ...

Developing a system for monitoring email open rates and geographical analytics using JavaScript?

I'm embarking on a project to develop an email tracker that can create a distinct pixel and monitor open rates using JavaScript with MeteorJS. Are there any valuable resources out there that could help me achieve this goal? I've come across exam ...

Customize a web template using HTML5, JavaScript, and jQuery, then download it to your local device

I am currently working on developing a website that allows clients to set up certain settings, which can then be written to a file within my project's filesystem rather than their own. This file will then have some parts overwritten and must be saved ...

Issue with Struts 2 tag causing malfunction in validating the collection

When iterating through a list in a JSP file using Struts 2 tags, the code below is used: <%@ taglib prefix="s" uri="/struts-tags"%> <head> ... The issue arises with date validation. The following line of code does not work: <td><s:d ...

Is there a way to track the loading time of a page using the nextjs router?

As I navigate through a next.js page, I often notice a noticeable delay between triggering a router.push and the subsequent loading of the next page. How can I accurately measure this delay? The process of router push involves actual work before transitio ...

The type 'number | { percent: number; }' cannot be assigned to the type 'string | number | undefined' according to ts(2322) error message

Presently, I am engaged in a project utilizing React and Typescript, where I am working on implementing a progress bar using react semantic-ui. I have encountered a typescript error in my code. Here is the segment causing the issue: import React, { Compo ...

Can TypeScript support promise chaining in a functional way?

It appears that in the realm of JavaScript, one has the capability to execute: function extendPromise(promise) { return promise.then(new Promise(() => {})); } However, when incorporating types into the mix, such as function extendTypeScriptPromis ...

Upon clicking, the Bootstrap dropdown button fails to open up

Recently while working on my Ruby on Rails project, I encountered an issue with implementing a dropdown button similar to the one on Bootstrap's site. Unfortunately, the button isn't functioning as expected and is throwing an error in the browser ...

What is the best way to decrease the border width of a chartjs doughnut chart?

I have a vision for my chart based on the mockup: However, here is what I've been able to achieve using chartjs so far: This is the code I'm working with: datasets: [ { data: [3, 8, 13, 9, 2], backgroun ...

Issues with utilizing a generic type in an Arrow function in the Typescript Playground

When I try to use a generic type with an arrow function in Typescript Playground, I get an error message saying Cannot find name 'T' For more details, check out this link function hasAllProperties <T>(obj: any, props: (keyof T)[]): obj is ...

The API call is successful, however the data is empty when returned in the callback function

Utilizing npm Express and Request modules, I am retrieving movie information through an API: var express = require("express"); var app = express(); var request = require("request"); app.get("/results", function(req, res){ console.log(getBody("http:// ...

How to resolve undefined Axios Authorization headers in Vue.JS and Node.JS interactions?

Encountering an issue while trying to set authorization headers for my axios instance. Here is the code snippet from my Vue.JS application running on http://localhost:8080 : axios.defaults.headers.common['Authorization'] = 'Bearer ' ...

A guide on extracting data from a Bootstrap table and removing a specific row

In my ejs file, I have a Bootstrap table set up as shown below. I am trying to implement a feature where clicking a button will trigger my del() function to delete the selected row. However, I am facing an issue where my function does not receive the &apos ...

Emphasize the Jqgrid row when clicked on, but do not check the multiselect checkbox

Is there a method in jQgrid to highlight a row when clicked without selecting the multiselect checkbox? I attempted using Multiboxonly = true as suggested by Oleg on Your assistance would be greatly appreciated, as this issue is currently hindering progr ...

Show Data on the Right-hand Side

Objective: Arrange the component names in two columns - left and right, with different objects like input textboxes based on a browser width of 981px. The desired layout is showcased in this link "https://jsfiddle.net/2w9kskr2/". Challenge: After impl ...

An error message pops up when using Next.js with Sass, indicating that a suitable loader is required to handle this file type

I've been struggling to properly wire up my next.js project with SCSS, but no matter what I try, it just won't work. I double-checked my setup for compiling SCSS files, but the error message keeps popping up: /scss/style.scss 1:0 Module parse f ...

Using Redux to Implement Conditional Headers in ReactJS

I am planning to develop a custom component named HeaderControl that can dynamically display different types of headers based on whether the user is logged in or not. This is my Header.jsx : import React from 'react'; import { connect } from &a ...

What is the best way to trigger actions from child components within React Redux?

My server contains the following code snippet: <ReactRedux.Provider store={store}><Layout defaultStore={JSON.stringify(store.getState())}/></ReactRedux.Provider> The <Layout> component includes more nested components. Further dow ...