Angular Checkbox Click EventLearn how to handle click events on

How can I toggle the visibility of a form using ngIf when a click event is triggered by a checkbox?

Below is the code for my column header and column values:

<th><label class="btn btn-filter">
    <input type="checkbox" name="allTrades" [value]="trade" (change)="allTrades($event)"> status
  </label> </th>

The status column has checkboxes next to it like this:

<td><ng-container *ngFor="let trd of trade">
    <label class="btn btn-filter">
      <input type="checkbox" name="trades" [checked]="trd.selected" (change)="yourfunc($event)" (change)="handleSelected($event)">{{ trd.label}}
    </label> 
  </ng-container></td>

When clicking the checkbox in the column header, all checkboxes in the column get enabled or disabled accordingly.

I want to show specific content when the checkbox is enabled. Here's the HTML chunk that should be shown/hidden based on the checkbox status:

<div *ngif=ischeck>
  
    <mat-form-field class="example-full-width">
        <input class="toolbar-search" type="text" matInput autocomplete="off">
        <mat-placeholder>Name</mat-placeholder>
    </mat-form-field>
    <mat-form-field class="example-full-width">
        <input class="toolbar-search" type="text" matInput autocomplete="off">
        <mat-placeholder>City</mat-placeholder>
    </mat-form-field>

</div>

Here's the typescript file with the functions used to handle the checkbox behavior:

 trade = [
  { label: ' Check', selected: false }, 

];

allTrades(event) {
      const checked = event.target.checked;
      this.trade.forEach(item => item.selected = checked);
}

handleSelected($event) {
  if ($event.target.checked === true) {
    // Handle your code
    this.ischeck=true
  }
}

Please note that the provided checkbox functionality will apply changes to all related checkboxes in the column.

You can find the interactive demo at this StackBlitz link.

Clicking the status checkbox will automatically update the other checkboxes. Now, the goal is to display additional content within the div tag when the checkbox is enabled.

Answer №1

To properly maintain the state of checked items, make sure to save it within the model being used instead of creating a separate variable like isChecked.

If you need an example of how to implement this, check out this functional solution: https://stackblitz.com/edit/angular-ivy-kfycuc

Remember to nest the div inside the ng-container for correct organization:

<ng-container *ngFor="let trd of trade">
  <label class="btn btn-filter">
    <input type="checkbox" name="trades" [checked]="trd.selected" (change)="handleSelected($event, trd)">{{ trd.label}}
  </label>&nbsp;

  <div *ngIf="trd.selected">
    <h1>Hey there!</h1>
  </div>
</ng-container>

Additionally, ensure that your handler function updates the model correctly:

handleSelected($event, trd) {
  trd.selected = $event.target.checked;
}

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

The jQuery method serializeArray does not include the values of HTML textareas and checkboxes

Hello, I'm looking to send data to the server from an HTML form. The server I'm using is CodeIgniter and I'm utilizing the AJAX method. Here's the HTML form: <div id="fileupload"> <form id="upload-media-form" class="uploa ...

Selecting a radio button by clicking on its corresponding label within an Angular Material dialog

I recently implemented a custom rating bar in Angular, which worked perfectly fine in a basic component. However, when I tried to move it to a MatDialog component, I encountered some issues. In the initial setup, my input was set to display: none so that t ...

Type guards do not work properly on a union of enum types in TypeScript

Recently delved into the concept of Type Guards Chapter within the realm of Typescript However, I encountered an issue where my basic type guards failed to differentiate a union of enums. Why is this happening? enum A { COMMA = ',', PLUS = & ...

Different results are being obtained when destructuring props in a component

Just diving into the world of React and trying to grasp destructuring. I've been doing some reading on it, but I'm currently stuck. When I try to destructure like this function MList({action}) { // const data = [action];}, I only get 'camera ...

Operating on a MacOS platform, the combination of Visual Studio 2019 with the Typescript and Sass

Currently, I'm facing a challenge with compiling my TypeScript to Javascript and Scss to css in Visual Studio 2019 (MVC .Net Core). Every compiler I've tried seems to be failing. Is there anyone out there who knows the process for accomplishing t ...

MongoDB NextJS connection issue "tried to retrieve a connection from a closed connection pool"

I am attempting to establish a connection to my MongoDB database in order to retrieve some information. When setting up the connection without fetching any data, everything works fine. However, when trying to fetch data, the console throws this error: at ...

Understanding the complexity of defining the type of a function can be challenging. If you're tasked with a complicated function, determining its type

Let's break it down: Dict is defined as { [key: string]: () => any } The desired return value is represented by X I am attempting to create a type for a function that: Takes in a dictionary Dict T Returns an X Now, X also functions as a functio ...

How do I use [(ngModel)] to set custom multiple select with 'selected' options with Angular and Materialize CSS?

Below is a snippet of code I am working with: <div class="input-field col s12"> <select name="uniqueName" [(ngModel)]="model.servicesIds" multiple> <ng-container *ngFor="let service o ...

A step-by-step guide on updating a deprecated typings package manually

Currently, I am developing a NodeJS application using TypeScript and incorporating numerous Node packages. However, not all of these packages come with TypeScript definitions, so Typings is utilized to obtain separate definition files. During the deployme ...

Protractor's Page Object returning inaccurate count

I am currently working on writing e2e tests for an Ionic app using Protractor and Cucumber. I have implemented a page object pattern, but I am facing an issue where the call to count() is returning 0, even though I have waited for the elements to be presen ...

Angular Regular Expression Directive

I am attempting to develop an Angular Directive in Angular 7 that allows users to input a RegExp through an input property and restricts them from typing characters that do not match the specified RegExp pattern. While it is partially functional, I am enc ...

Update ng-Bootstrap ToDate field by removing the date when selecting a fromDate

Is there a way to clear the date from the toDate input field while selecting a date from the fromDate input field in ng-bootstrap? <form class="row row-cols-sm-auto" *ngIf="showDateRangeImp"> <div class="col-12" ...

When using this.$refs in Vue, be mindful that the object may be undefined

After switching to TypeScript, I encountered errors in some of my code related to: Object is possibly 'undefined' The version of TypeScript being used is 3.2.1 Below is the problematic code snippet: this.$refs[`stud-copy-${index}`][0].innerHTM ...

Angular9: construction involves an additional compilation process

After updating my Angular8 project to Angular9, I noticed a new step in the build process which involves compiling to esm. This additional step has added approximately 1 minute to my build time. A snippet of what this step looks like: Compiling @angular/ ...

There has been no answer provided. Could this be due to being utilized in an asynchronous function that was not returned as a promise?

I encountered the following error message: Error: No response has been set. Is this being used in an async call that was not returned as a promise to the intent handler? at DialogflowConversation.response (/user_code/node_modules/actions-on-google/dis ...

Ways to prevent altering values in ngModel

I am working on a component in Angular 5 where I am trying to write unit tests to ensure that when the component is disabled, it should not be possible to set a value to its model. However, even after disabling it, I am still able to change the value. [ ...

The error message indicates that the Python executable "C:UsersAdminAnaconda3python.EXE" cannot be found, but you have the option to configure the PYTHON environment variable as a workaround

After downloading a project from github, I attempted to run npm install in my application. Unfortunately, I encountered the following error: > [email protected] install C:\Users\Admin\Desktop\New folder\flow\node_modu ...

Angular 2: It is essential to have a distinct instance for Signature Pad

I am seeking assistance with utilizing the signature pad feature in order to capture multiple signatures. Below is a snippet of my code. I have 'n' number of employees and would like each employee to input their signature into the designated box ...

Display only a specific range of years on the Angular Material Date picker. For example, show only the dates from 1950 to the current year, excluding any other years outside of this range

In my current project, I am utilizing the Angular Material Datepicker for selecting dates. Does anyone know how to display only a specific range of years? For example, I need to show years starting from 1950 in my Material Date Picker and remove any years ...

Strange occurrences with HTML image tags

I am facing an issue with my React project where I am using icons inside img tags. The icons appear too big, so I tried adjusting their width, but this is affecting the width of other elements as well. Here are some screenshots to illustrate: The icon wit ...