Confirm whether an angular2 input checkbox has been checked or not

I have implemented a table in my HTML with an input checkbox present in each row.

Currently, I am attempting to determine whether the checkbox has been selected or not. Below is the approach I have taken:

HTML:

<table class="table table-hover" id="just_a_table">
    <thead>
        <tr>
          <th scope="col">Select</th>
          <th scope="col">IP Addr</th>
        </tr>
    </thead>
    <tbody>
        <tr *ngFor="let data of instances">
          <td><input type="checkbox" (click)='onSelect()'></td>
          <td>{{data["IP"]}}</td>
        </tr>
    </tbody>
</table>

TS:

onSelect() {
    // Get table data from the html and check if the checkbox is active.
    // Access rows of the table using "rows" object and cells using "cells" object.
    this.table_data = document.getElementById("just_a_table")

        for (var i=1, row; row = this.table_data.rows[i]){
          for (var j=0, cell; cell = row.cells[j]){
            if (<HTMLInputElement>cell[1].checked){
              console.log("It is checked")
            }
        }
    }
}

I decided to take this method as I prefer not to target the input element by its ID to check its status.

If you have any suggestions or guidance on how I can achieve this more efficiently, it would be greatly appreciated.

Answer №1

Customized HTML Code

 <table id="custom_table" class="custom-table">
       <thead>
           <tr>
               <th scope="col">Selection</th>
               <th scope="col">IP Address</th>
           </tr>
        </thead>
        <tbody>
           <tr *ngFor="let data of instances">
               <td><input type="checkbox" (change)='onSelect($event)'></td>
               <td>{{data["IP"]}}</td>
           </tr>
        </tbody>
   </table>

To resolve the issue, remember to utilize event.target.checked. Here's how you can implement it:

Updated TypeScript Function

onSelect(event) {
     if ( event.target.checked ) {
        // Add your logic here
    }
}
  1. Ensure to use (change) over (click) for better practice
  2. Avoid reliance on vanilla JS when using Typescript and Angular, as these frameworks enhance development efficiency

Answer №2

To begin, I recommend utilizing the Angular (click) event binding and adjusting your ngFor loop as follows:

<tr *ngFor="let data of instances; let i = index" [attr.data-index]="i">

This modification allows us to easily identify which checkbox is selected.

<table class="table table-hover" id="just_a_table">
    <thead>
        <tr>
          <th scope="col">Select</th>
          <th scope="col">IP Addr</th>
        </tr>
    </thead>
    <tbody>
        <tr *ngFor="let data of instances; let i = index" [attr.data-index]="i">
          <td><input type="checkbox" value="false" (click)='onSelect($event, i)'></td>
        </tr>
    </tbody>
</table>

Next, initializing an array with false values matching the length of instances would be beneficial if you require knowledge of the checked checkboxes. While there are alternative approaches, this one is straightforward.

constructor() {
    for (let i = 0; i < this.instances.length; i++) {
        this.resultArray.push(false);
    }
}

Utilize event.target.checked to determine the checked status of the clicked checkbox. Then, based on the index, update the corresponding array element. Ensure to include the parameters in the function definition as well.

onSelect(event, index) {
    // If checking which checkboxes are selected is necessary
    this.resultArray[index] = event.target.checked;
    // If not required
    const result: EventTarget = event.target.checked;
    // Perform appropriate actions with the value
}

Answer №3

<div *ngFor="let item of data">
   <p><input type="checkbox" (click)='toggleSelection($event)'></p>
   <p>{{item["name"]}}</p>
</div>


toggleSelection(event) {
    if (event.target.checked) {
       // add your logic here.
        console.log('checked', event.target.checked);
       }

Hope this solution works for you!! :)

Answer №4

function checkSelectedCells() {
    let table = document.getElementById("just_a_table");
    for (let i = 1; i < table.rows.length; i++){
        for (let j = 0; j < table.rows[i].cells.length; j++){
            if (table.rows[i].cells[j].children[0].checked){
                console.log("This cell is checked");
            }
        }
    }
}

Answer №5

***************************************************************

Give this a try:

Declare a Boolean variable called checkBoxValidate

Initialize the variable to false in the ngOnInit() method: this.checkBoxValidate = false;

<table class="table table-hover" id="just_a_table">
    <thead>
        <tr>
            <th scope="col">Select</th>
            <th scope="col">IP Addr</th>
        </tr>
    </thead>
    <tbody>
        <tr *ngFor="let data of instances">
            <td><input type="checkbox" (click)='onSelect()'></td>
            <td>{{data["IP"]}}</td>
        </tr>
    </tbody>

TypeScript

onSelect()
{
    if(this.checkBoxValidate == false)
    {
        this.checkBoxValidate = true;
    }
    else
    { 
        this.checkBoxValidate = false;
    }
}

If checkBoxValidate is true, checkbox is checked, otherwise it is unchecked

***************************************************************

Answer №6

To implement in angular 2+, follow the example below:

<div class="togglebutton">
                                            <label>
                                                <input type="checkbox" [checked]="record.isStatus" (change)="changeStatus(record.id,$event)">
                                                <span class="toggle"></span>

                                            </label>
                                        </div>

In your TypeScript file:

changeStatus(id, e) {
        var status = e.target.checked;
        this._companyHubService.addOrRemoveStatus(id, status).subscribe(result => {
            this.modalSave.emit();
            if (status)
                this.notify.success(this.l('AddedAsStatus'));
            else
                this.notify.success(this.l('RemovedFromStatus'));

        });
    }  

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

Expanding the default Stackblitz App component with additional standalone Angular components?

I have recently developed a separate AppNavComponent component on Stackblitz platform. import { Component } from '@angular/core'; import { CommonModule } from '@angular/common'; import { RouterOutlet } from '@angular/router'; ...

Leveraging RXJS to retrieve a singular value from an observable without any alterations

Looking for a solution to create a wrapper service for Angular 2's Http Service that can save the returned Headers without altering the original Observable? The main goal is to make any call to an Angular 2 Http method (e.g. http.get()) and then retri ...

You cannot directly access an array useState by index in React js, but you can use the map function to

export interface JobListing { id: number, isTraded: boolean, feedback: string, title: string, message: string, skills: string[], sender: string, ipAddress: string } const GroupList = () => { const [jobListings, setJobListings] = useSt ...

Using Angular2 to import components and services from a module

I am currently developing a final Angular2 application with two modules: CoreModule: This module includes shared components and services. AppModule: The main module of the application. AppModule: /** * Created by jamdahl on 9/21/16. */ // Imports impo ...

Obtain the refresh token from Azure AD using ADAL for Angular

I am currently utilizing the "adal-angular6": "1.0.68" version. Below is my current configuration: private config = { tenant: environment.appId, // representing the tenantId. clientId: environment.clientId, redirectUri: environment.origin ...

Learn the method for triggering events with a strongly-typed payload in Vue 3 Composition API and TypeScript

I'm currently exploring Vue 3 Composition API along with TypeScript, particularly focusing on emitting events with a strictly typed payload. There's an example provided below, but I'm unsure if it's the most effective way to achieve t ...

The parameter 'X' cannot be assigned to the argument of type 'X'

Hello there! I'm diving into Type Script for the first time with VSCode. Encountering these errors: error TS2322: Type '() => string' is not assignable to type 'string'. error TS2322: Type '() => number' is ...

What is the best way to show the character count for every input in an Angular application?

In my app component, I have two input fields. I want to display the character count and max character limit for each input field dynamically as users type or blur on the input field. To achieve this, I created a component that shows and hides the characte ...

agm-info-window - Adjusting position to the right

Currently, I am using angular google maps to display maps along with markers and info windows. The issue I am facing is that the info window always appears on top. Is there a way to change its position to the right instead? <agm-map [latitude]="lat" ...

Experiencing the issue of receiving unexpected commas following a div

Here is the code written in TypeScript for creating an HTML table that displays items from nested objects. The code is functional, but there seems to be an issue with extra commas being printed which are not part of any specific line being executed. im ...

Simulate an array within an Angular Component class

How can I simulate an array in Angular tests? myComponent.ts //variable declaration certificateArray: any[] = []; getCert(certName:any){ for (let index in this.certificateArray) { //perform some action } } myComponent.spec.ts it('should display def ...

Tests in headless mode with Cypress may fail sporadically, but consistently pass when running in a real browser

Currently, I am utilizing Cypress 9.5 to conduct tests on an Angular 13 application with a local PHP server as the backend. Throughout the testing process, I have encountered successful results when running the tests in the browser multiple times. However ...

What is the process for obtaining an HTML form, running it through a Python script, and then showcasing it on the screen

I am inquiring about the functionality of html and py script. .... The user enters 3 values for trapezoidal data from the html form: height, length of side 1, and length of side 2, then clicks submit. The entered values are then sent to be calculated using ...

What are the necessary steps to deploy Angular 2 universal starter on a third-party server host such as Google Cloud or Azure?

I recently cloned the universal-starter (webpack version) repository and successfully got it running on my local machine using npm start and npm run watch as per the provided instructions. However, I hit a roadblock after running npm run build and trying ...

Exploring the Way Constructors are Utilized with Decorators in TypeScript

Encountering issues when attempting to utilize constructor spreads with decorators in TypeScript, here is the code snippet: export function httpGet(path?: string, ...middlewares : Function[]) { }; Usage example: class Controller { @httpGet('/:id& ...

An issue has occurred: the function cannot be applied to the intermediate value that is currently being processed

I am currently working on an Angular 5 CRUD application, utilizing Google Firebase services. I have been following a helpful video tutorial on YouTube (link here), but I encountered this error ngOnInit() { var x = this.employeeService.getData(); x.sna ...

Angular Pipe: Working with Data Structures in Angular With Nested Arrays and Objects

After struggling to customize answers for similar questions, I find myself in need of some assistance. My current challenge involves using an angular pipe to filter the following data structure: subjects = [ { name: "subject1", keywords:[& ...

Having trouble getting Tailwind CSS utility classes to work with TypeScript in create-react-app

I have been struggling to troubleshoot this issue. I developed a React application with TypeScript and integrated Tailwind CSS following the React setup guidelines provided on the official Tailwind website here. Although my code and configuration run succ ...

Prettier seems to be producing varied outcomes across various machines

My teammate and I are collaborating on the same project, but we're facing an issue where our Prettier configurations conflict. Each time we push our code to Github, his Prettier format overrides mine. Here's an example of his formatting: const in ...

A collection of named functions within a Typescript interface

I'm trying to understand how the code below will create an object that contains 2 functions. I haven't been able to locate any documentation on this specific pattern. interface FooContext { bar(a: A, b: B[]): boolean; baz(a: A, b: B[]): boole ...