pick only one option from each row

I am working on a feature where I have five rows with two checkboxes each generated using a loop and property binding. Currently, clicking on one checkbox selects all elements in the column. However, I want to achieve selection row-wise. Is there a method to achieve this?

my component.ts

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

enum CheckBoxType { APPLY_FOR_JOB, MODIFY_A_JOB, NONE };
@Component({
  selector: 'app-select-fav',
  templateUrl: './select-fav.component.html',
  styleUrls: ['./select-fav.component.css']
})
export class SelectFavComponent implements OnInit {
  public fruits = ["apple", "straw berry","orange","plum","grapes"]

  check_box_type = CheckBoxType;

  currentlyChecked: CheckBoxType;

  selectCheckBox(targetType: CheckBoxType) {
    // If the checkbox was already checked, clear the currentlyChecked variable
    if(this.currentlyChecked === targetType) {
      this.currentlyChecked = CheckBoxType.NONE;
      return;
    }

    this.currentlyChecked = targetType;
  }
} 

my component.html

<button>Like All</button>
<div *ngFor="let item of fruits;  let i = index">
    <p>{‌{item}}</p>
    Like: <input type="checkbox" name="test" 
    [checked]="currentlyChecked === check_box_type.APPLY_FOR_JOB" 
    (click)="selectCheckBox(check_box_type.APPLY_FOR_JOB)">

    Dislike : <input type="checkbox" name="test"
    [checked]="currentlyChecked === check_box_type.MODIFY_A_JOB" 
    (click)="selectCheckBox(check_box_type.MODIFY_A_JOB)">
    <hr>
</div>

PS: Clicking on the button should check all the like checkboxes in each respective row.

Answer №1

If you're facing an issue, it might be because you are attempting to manage a one-to-many relationship with your current approach. A better way to handle this is by organizing your data in a way that captures the characteristics of each object (in this case, the fruit). Utilizing [(ngModel)] will help you establish the necessary bindings.

For a hands-on example, check out this Stackblitz Sample

TypeScript

import { Component, OnInit } from '@angular/core';
enum CheckBoxType { LIKEME, DISLIKE, NONE };
@Component({
  selector: 'app-select-one',
  templateUrl: './select-one.component.html',
  styleUrls: ['./select-one.component.css']
})
export class SelectOneComponent implements OnInit {
  public fruits = ["apple", "straw berry","orange","plum","grapes"].map( f => ({ name: f, like: false, dislike: false }));
  check_box_type = CheckBoxType;

  currentlyChecked: CheckBoxType;
  constructor() { }

  ngOnInit() {}

  selectAllLike(){
     this.fruits.forEach( f => {
       f.like = true;
       f.dislike = false;
     })
  }
}

HTML

<button (click)="selectAllLike()" >Like All</button>
<div *ngFor="let item of fruits;  let i = index">
    <p>{{item | json}}</p>
    Like: <input type="checkbox" name="test" [(ngModel)]="item.like" [disabled]="item.dislike">

Dislike : <input type="checkbox" name="test" [(ngModel)]="item.dislike" [disabled]="item.like">
    <hr>
</div>

Additionally, consider using Angular Material's MatTable for tabular layouts as it offers a more polished and comprehensive solution.

Angular Material Table Overview

To see another approach using toggling states through a function, refer to:

Alternate Example on Stackblitz

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

NestJS TypeORM InjectRepository throwing an error: "Cannot access property 'prototype' of undefined"

Encountering an issue while trying to unit test. Here is the error message that I received: TypeError: Cannot read property 'prototype' of undefined export class UserService { constructor(@InjectRepository(User) private readonly userRepository ...

Tips for correctly decorating constructors in TypeScript

When a class is wrapped with a decorator, the superclasses lose access to that classes' properties. But why does this happen? I've got some code that demonstrates the issue: First, a decorator is created which replaces the constructor of a cla ...

Unable to proceed due to lint errors; after conducting research, the issue still remains

I'm still getting the hang of tslint and typescript. The error I'm encountering has me stumped. Can someone guide me on resolving it? I've searched extensively but haven't been able to find a solution. Sharing my code snippet below. (n ...

Error when building Angular 9 due to missing peer dependencies

In my coding project, there is a specific npm module that has a dependency on electron. The functionality from this module is accessed within a function and only executed when necessary, allowing it to be utilized in both electron-based projects as well as ...

The ace.edit function is unable to locate the #javascript-editor div within the mat-tab

Having trouble integrating an ace editor with Angular material Error: ace.edit cannot locate the div #javascript-editor You can view my code on StackBlitz (check console for errors) app.component.html <mat-tab-group> <mat-tab label="Edito ...

Showcasing a recently incorporated mat-card

I have a collection of mat-cards that are being displayed using data received through an observable called cars$. Each time a new car object is emitted by this observable, a new mat-card appears automatically. Is there a way to make the newly added mat-c ...

Guide to creating unit tests for a button click function in an Angular project

I wrote some code for unit testing, but it doesn't seem to be working. I'm new to unit testing and would appreciate some guidance on how to use it. COMPONENT.HTML <button class="set-button" (click)="clickFunction()"> SA ...

Error: Angular encountered an undefined variable when attempting to import 'node_modules/bootstrap/scss/grid'

Having some trouble setting up Angular with SCSS and Bootstrap. When attempting to run ng serve, I encountered the following error: ./src/styles.scss - Error: Module build failed (from ./node_modules/sass-loader/dist/cjs.js): SassError: Undefined variable. ...

Notification from the background has been received and parameters have been restored

Sending a post request from "angular->port 4200" to "expressjs server->port 8000". Referencing this example: https://github.com/kuncevic/angular-httpclient-examples/blob/master/client/src/app/app.component.ts Encountering two errors: 1) Undefined respon ...

Enhancing CKEditor functionality with Angular 2 for improved textarea usage

Check out this Plunker example: https://plnkr.co/edit/aUBtpe?p=preview When using CKEditor, the value of the content variable does not update when changes are made to the textarea. It remains the same as the original page.content variable that was obtaine ...

Typescript's spellbinding courses

I'm encountering some issues with Typescript and the "@botstan/Magic" library in nodejs. Before we proceed, please take a look at the "Magic" documentation. Follow these lines: import Magic from "@botstan/magic"; import * as _ from "lodash"; @ ...

Tips for generating a JSON-driven table in Angular 2

I'm attempting to build a dynamic datagrid in angular2 using a JSON object as the source. The challenge I face is not knowing the structure of the columns within the table, making it difficult to render the rows properly. My understanding is that I n ...

Limit function parameters to only accept values with matching keys

I am relatively new to using TypeScript and am currently working on a project that involves handling various shapes of data from different sources. My goal is to pass this data to different aggregator classes, with one aggregator class corresponding to eac ...

After updating from angular4 to angular 5, the npm test is failing with the error message "TypeScript compilation cannot find test.ts file"

After upgrading my app from Angular4 to Angular 5 using the steps provided on https://update.angular.io/, I encountered an issue. While I can successfully run ng-serve and ng build without any problems, the npm test command for ng test is failing with the ...

Encountered an issue when attempting to post to an ASP.NET Core Web API utilizing Windows authentication

The setup consists of an AspNetCore WebApi using default configuration for Windows authentication and CORS enabled. The client side utilizes Angular with both GET and POST methods implemented. Successfully executing the GET call: this.http.get("https://l ...

Navigating in an Electron app using Angular

It appears that I am encountering difficulties with routing pages in my angular electron desktop application. Despite configuring the routing similar to an angular app, nothing seems to be functioning properly. I have specified router links such as "/hom ...

Using TypeScript with Node.js: the module is declaring a component locally, but it is not being exported

Within my nodeJS application, I have organized a models and seeders folder. One of the files within this structure is address.model.ts where I have defined the following schema: export {}; const mongoose = require('mongoose'); const addressS ...

Outputting data stored in Firestore object

Is there a way to display the content of a Firestore object in Angular Firebase? I am working on a project where I need to retrieve and print the name of a document stored in Firestore. In my Firestore database, I have a parent collection called "nforms" w ...

Error handling: Encountered unexpected issues while parsing templates in Angular 2

I'm a beginner with Angular 2 and I'm attempting to create a simple module, but encountering an error. app.component.html import { Component } from '@angular/core'; import { Timer } from '../app/modules/timer'; @Component({ ...

The content security policy is preventing a connection to the signalr hub

Currently, I am developing an application using electron that incorporates React and Typescript. One of the features I am integrating is a SignalR hub for chat functionality. However, when attempting to connect to my SignalR server, I encounter the followi ...