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

There are a few steps to take in order to sort an array of objects by a

I want to organize and display data in a sortable table format javascript let dataList = [ { idx: number, name: string, btn: number, index: number }, { idx: number, name: string, btn: number, index: number }, { idx: number, name: string, btn: number ...

Adding an object to an array in Postgres with TypeORM

I am currently facing an issue with the column in my Postgres database that has a data type of json. The code snippet for this scenario is as follows: @Column({ type: 'jsonb', nullable: false, default: [] }) us ...

The category 'Moment' cannot be assigned to the category 'Date'. The characteristic 'toDateString' is not present in the category 'Moment'

I recently integrated moment into my Angular2 application, and encountered an issue when attempting to assign the date of this week's Saturday to a variable of type date, case "weekend": this.fromDate = moment().startOf('week ...

Is there a way to modify the id parameter in the URL using Angular 2's ActivatedRoute?

How can I modify a parameter in the URL without altering the overall address? https://i.stack.imgur.com/LOd4T.png This is the TypeScript code that I currently have: onRowClicked(event: any) { let currentIdPerson = event.data.IdPerson; } I am trying ...

Avoid saying the same thing more than once

Within my Typescript class, I have the following structure: class C { #fsm (...) startFoo(name: string) { this.#fsm.send('FOO', name) return this } startBar(name: string) { this.#fsm.send('BAR', name) return th ...

Tips for incorporating jQuery UI into Angular 6

No matter how many methods I have tried from StackOverflow, I cannot seem to get jquery-ui to work in my angular 6 component. Here's what I've attempted: I went ahead and ran npm install jquery jquery-ui to install both jquery and jquery-ui. ...

Utilize Angular 5 to implement document uploads through a REST service call

I've been attempting to upload a document to our repository using Angular 5 and I'm encountering an error that I've included below. The Multipart/Form code is very similar to what worked in Angular 1.x, except for one line difference in the ...

AG-Grid: Enhancing Cell Interactivity

Within ag-grid, there is a feature called stopEditingWhenGridLosesFocus. I recently developed my own custom cell editor using a cell editor component. I am curious to know if there exists a similar property or method to achieve the behavior of stopEditing ...

Troubleshoot Issue with Installation of angular2-jwt.js and Provide Solutions for Error Code

I am currently following the installation guidelines to install Respond CMS from Github. My progress has hit a snag while attempting to copy files to the public folder using gulp. and it's the third command in step 2. This brief error message aris ...

Unexpected behavior: ng2-dragula modelDrop event leading to undefined array

Struggling to figure out the issue with this code. As shown in this GIF, when dragging a div from one container to another, the object disappears and the array becomes undefined. https://i.stack.imgur.com/TELyc.gif Here is the code snippet: Main View.ht ...

Retrieve the text content of the <ul> <li> elements following a click on them

Currently, I am able to pass the .innerTXT of any item I click in my list of items. However, when I click on a nested item like statistics -> tests, I want to display the entire path and not just 'tests'. Can someone assist me in resolving this i ...

Creating a currency input field in HTML using a pattern textbox

In a project using HTML, Angular 2, and Typescript, I am working with a textbox. How can I ensure that it only accepts numbers along with either one dot or one comma? The input should allow for an infinite number of digits followed by a dot or a comma and ...

Vue's span function is yielding the promise object

In my Vue component, I am using the function getOrderCount to fetch the number of orders from a specific URL and display it in one of the table columns. <div v-html="getOrderCount(user.orders_url)"></div> async getOrderCount(link) { ...

Is there a way to automatically select all checkboxes when I select contacts in my case using Ionic 2?

initializeSelection() { for (var i = 0; i < this.groupedContacts.length; i++) { for(var j = 0; j < this.groupedContacts[i].length; j++) this.groupedContacts[i][j].selected = this.selectedAll; } } evaluateSelectionStatus() { ...

Implementing a GIF loader in your webpack configuration for a Typescript/React/Next.js application

Upon inserting a .gif file in my Typescript React app, an error message has surfaced. ./src/gif/moving.gif 1:6 Module parse failed: Unexpected token (1:6) You may need an appropriate loader to handle this file type, currently no loaders are configured to p ...

Allow consumers of the component to customize the ChangeDetectionStrategy

Imagine a scenario where a component in a UI library is configured with ChangeDetectionStrategy.Default, but wants to offer the flexibility for consumers to switch to ChangeDetectionStrategy.OnPush (especially for performance considerations) using an Input ...

Unit Testing in Vue.JS: The original function remains active even after using sinon.stub()

While unit testing my components (which are coded using TypeScript along with vue-class-component), I am utilizing Sinon to stub API calls. However, even after adding the stub to the test, the original method is still being invoked instead of returning the ...

Assigning value to a member variable in a TypeScript Angular class

Currently, I am in the process of learning Angular. To enhance my skills, I am developing a simple web application using Angular and Spring Boot. One challenge I encountered is assigning a variable to the member variable of a Class. import { Injectable } f ...

What is the best way to organize a material table with favorites prioritized at the top?

My goal was to customize the sorting of a mat-table in Angular, ensuring that the "favorite" items always appear at the top of the table. I aimed for the favorite items to maintain their position as the first items in the table regardless of any other sor ...

Executing a Prisma query with a selection

My Prisma models involve User, Car, and Reservation entities: model User { id String @id @default(auto()) @map("_id") @db.ObjectId name String? email String? @unique emailVerified DateTime? image ...