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

Analyzing arrays and object key/value pairs based on a specific value in javascript

I want to create a new object with key/value pairs. The new object should include values from an existing key/value object as well as unique values from an array. Here is the array: [{ name: "Computer", name: "Car", name: "House&q ...

The object's null status remains uncertain even after being checked for null

Currently, I am working with Typescript 2.8 This is the code snippet that I have: class Wizard extends React.Componenet { private divElement: null | HTMLDivElement = null; componentDidUpdate(_: IWizardProps, prevState: IWizardState) { i ...

Error: The page "..." contains an invalid "default" export. The type "..." is not recognized in Next.js

Currently, I have a functional component set up for the Signup page. My goal is to define props within this component so that I can pass the necessary values to it from another component. This is my current approach: export default function SignupPage({mod ...

Steps for adjusting the length in the getRangeLabel function of mat paginator

@Injectable() export class MyCustomPaginatorIntl extends MatPaginatorIntl { public getRangeLabel = (page: number, pageSize: number, length: number): string => { if (length === 0 || pageSize === 0) { return `${ ...

Resolving Node.js Troubles: An Encounter with 'Module Not Found' Error

After generating a new application, I encountered an error while using the "ionic serve" command. [ng] The specified path cannot be found. [ng] internal/modules/cjs/loader.js:883 [ng] throw err; [ng] ^ [ng] Error: 'C:\Users\shane\Co ...

Automate the process of opening an ngbpopover from an Angular 2 component using programming techniques

Currently, I am referring to this specific article in order to integrate Bootstrap with Angular 2. While the instructions in the article are helpful, there seems to be a lack of information on how to pass the popover reference to a component method. The on ...

Do I have to create all the classes returned when consuming a JSON web service in Angular/Typescript?

I would like to access this service: https://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&key=YOUR_API_KEY I am interested in extracting only two pieces of data: "location" : { " ...

Angular rxjs Distinctions

Coming from AngularJS to Angular, I'm still trying to wrap my head around rxjs observable. For example: User.ts export class User { id?:any; username:string; password:string; } Using <User[]> myUser(header: any) { const url = `${this.mainUr ...

Learning about React and TypeScript: Easy steps to import a component

Here is the structure of my react components in TypeScript: -App.tsx -NewRequestForm.tsx -EmployeeInfo.tsx -AssetInfo.tsx When trying to import EmployeeInfo & AssetInfo in NewRequestForm, only the Prop & State interfaces are visible, not the ...

Ways to return bsDateRangePicker to its default value

I'm currently working on creating reactive forms using Angular 9 and integrating ngx-bootstrap. One issue I am facing is with the daterangepicker functionality. Whenever I utilize the form.reset() function, it clears the input field entirely instead o ...

What is causing the issue with using transition(myComponent) in this React 18 application?

Recently, I have been immersed in developing a Single Page Application using the latest version of React 18 and integrating it with The Movie Database (TMDB) API. My current focus is on enhancing user experience by incorporating smooth transitions between ...

Transform JSON object array into a different format

Can anyone help me with an issue I am facing with checkboxes and arrays in Angular 2? I have checkboxes that capture the value "role". Each role is stored in an array called "selectedRoles". However, when I try to console.log this.selectedRoles, I get str ...

Tips for creating animations using parent and child components in Angular

Despite my best efforts, it seems like this should be functioning properly... but unfortunately it's not... I'm attempting to achieve a transition effect on the parent element (ui-switch-groove) while the child element (ui-switch-dongle) moves. ...

Unable to access /route upon refreshing page in Angular 7

After developing several components in Angular 7, I decided not to use 'useHash: true' for routing. Everything seemed to be running smoothly when I deployed my Angular app on a live server. However, I encountered an issue when reloading a page a ...

Struggling to send information to the data layer on every page in Angular 9

Currently, I am in the process of integrating a GTM snippet into my Angular project. However, I have noticed that when the page is hard reloaded, it pushes data but does not do so during normal navigation. I have already added the GTM snippet provided by ...

What steps are needed to have typescript recognize a typed function as a throw-statement?

I'm grappling with a typescript issue - I have a custom function that consistently throws an error, which is used to handle null variables. Strangely, if I directly throw an error without using the function, typescript recognizes that the variable can ...

Steps for sending HTTPS requests from Angular 6 to Node.js

In my MEAN stack app, I have Angular built in the public folder of Express to run the server on the same port. I also have a certificate from Cloudflare added to Node.js for HTTPS server, and my server is running on Nginx. I have opened port 443 on EC2, an ...

Having trouble getting matSort to work in Angular 8 as it keeps returning an undefined error when trying

Having trouble getting the mat sort functionality to work on my table, as it keeps showing as undefined. I've tried various solutions from the documentation but nothing seems to be working for me. (I have removed ngIf, changed static to false, and tr ...

Navigate to a specific route on Angular 5 with varying parameters

Can someone help me with navigating to the same route with different parameters? Currently, when I try to do this, it redirects me to a different route. However, if I press the back button, it takes me to the correct page. Any suggestions? Here are my rou ...

Subscription to Observable content failed to run

When a submit button is clicked inside the component HTML, it triggers a function called addCollaborators(). The code for this function can be found below: component.ts emails: string[] = []; constructor(public userService: UserService) {} // Function ...