Ways to toggle checkboxes to show or hide their child items and subitems

I'm working on creating a straightforward menu that allows users to click on a parent checkbox to expand or collapse its children. The challenge I'm facing is how to make the parent checkboxes expand while hiding the children items within them when clicked. Here's what I want the outcome to look like:

https://i.sstatic.net/sIGlk.png

Below is the function I've created for selecting or unselecting:

 selectUnselectAll(obj) {
    obj.isAllSelected = !obj.isAllSelected;
    // tslint:disable-next-line:prefer-for-of
    for (let i = 0; i < obj.ParentChildchecklist.length; i++) {
      obj.ParentChildchecklist[i].isSelected = obj.isAllSelected;
      // tslint:disable-next-line:prefer-for-of
      for (let j = 0; j < obj.ParentChildchecklist[i].choices.length; j++) {
        obj.ParentChildchecklist[i].choices[j].isSelected = obj.isAllSelected;
      }
    }
  }

This link takes you to the entire application:

Link to the app in stackblitz

Currently, my dressing and bread lists do not collapse at all. How can I make the children also collapse?

Any guidance on achieving this would be greatly appreciated.

Answer №1

If you want a more efficient way to handle form control changes, consider utilizing the valueChanges Observable from the parent controls and conditionally displaying it in the child controls container using *ngIf:

In TypeScript:

this.showBread$ = this.breadCtrl.valueChanges;

In HTML:

<input type="checkbox" [formControl]="breadCtrl">
<div class="bread-container" *ngIf="showBread$ | async">
  <!-- children here -->
</div>

This approach promotes the use of reactive forms which is highly recommended in majority of cases.

Update: Instead of manually checking boxes, you can utilize patchValue on each control (or their containing FormGroup) for a more Angular-friendly approach.

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

What steps should be followed to effectively incorporate Google Fonts into a Material UI custom theme for typography in a React/TypeScript project

Hey there, I'm currently working on incorporating Google fonts into a custom Material UI theme as the global font. However, I'm facing an issue where the font-weight setting is not being applied. It seems to only display the normal weight of 400. ...

Creating a new Angular2 component for a separate URL path

In my scenario, I have a PageComponent that gets refreshed with new data when the URL changes (using PageService). It currently utilizes the same PageComponent object, but I am looking to make it a new object when the URL changes. 1st Question: How can ...

Using TypeScript, a parameter is required only if another parameter is passed, and this rule applies multiple

I'm working on a concept of a distributed union type where passing one key makes other keys required. interface BaseArgs { title: string } interface FuncPagerArgs { enablePager: true limit: number count: number } type FuncArgs = (Fu ...

Methods for verifying an empty array element in TypeScript

How can I determine if an element in an array is empty? Currently, it returns false, but I need to know if the element is blank. The array element may contain spaces. Code let TestNumber= 'DATA- - -' let arrStr =this.TestNumber.split(/[-]/) ...

What is the best way to send an XML body using Angular 5 with POST method?

I am currently developing an Ionic application that needs to make REST API calls with XML as the body. However, I am facing issues in getting the call to post with XML. This is my LoginProvider where I utilize DOMParser to parse data to XML before sending ...

Angular error: Attempting to access the value property of an undefined object

When attempting to delete a row from a table, an error occurred stating "TypeError: Cannot read property 'value' of undefined" after placing the delete button at the end of a row. I watched this video tutorial for guidance on deleting a row witho ...

Utilizing ResolveComponentFactory() with a String Key: A Step-by-Step Guide

My goal: I want to find a way to use something similar to the "resolveComponentFactory()", but with a 'string' identifier to obtain Component Factories. Once I have them, I plan to utilize the "createComponent(Factory)" method. Check out this P ...

What could be causing the itemClicked() function to malfunction intermittently in Ionic2 / Angular2?

The issue at hand One common problem experienced with Angular's (click) functionality is that it may not work properly when <div> tags are utilized. In certain situations, multiple clicks might be required. I encountered the same problem mysel ...

Unveiling the types of an object's keys in Typescript

I am currently utilizing an object to store a variety of potential colors, as seen below. const cardColors = { primaryGradientColor: "", secondaryGradientColor: "", titleTextColor: "", borderColor: "&quo ...

In Angular, there is an issue where the @ViewChild decorator does not reflect changes when the value of the child component is updated within the

Does anyone know why the console.log("My status :", status); is not displaying after the child property has changed? Here is my child component code: @Output() public isLoggedIn: Subject<boolean> = new Subject(); constructor( private auth ...

Elements can only be added to the array at the 0th index

In the process of developing a function, I encountered an issue where all elements added to the array were only stored in Array[0] of the rowData. The data is retrieved from a database. private createRowData() { var rowData:any[] = []; thi ...

Setting up Angular Universal on an already existing Angular 2 application with the help of the CLI

Encountering obstacles while trying to integrate the universal CLI into an existing Angular 2 application by following the guidelines provided in this link: During the initial command to install angular-universal: npm install body-parser angular2-univers ...

Testing the creation of elements dynamically with jestLooking into jest for dynamically adding

Attempting to test a dynamic element using TypeScript, but struggling to understand the process. Can anyone offer guidance? Below is the TypeScript file: export default class MyClass { constructor(){ this.render(); } render() { ...

Implementing group validation with Angular

What is the proper validation method for a form group control with code length containing decimal fields? Currently, my code is as follows: this.control = new FormControl(val, [Validators.required, Validators.maxLength(items.CodeLength)]); However, I am ...

Issue encountered with Ionic and ssh2: process.binding is not supported

I am currently delving into the world of Ionic and experimenting with creating a basic application that utilizes SSH2 to establish an ssh connection between the app and a server. Here is a breakdown of the steps I took to encounter the issue: Steps to Rep ...

Is there a way to toggle or collapse a table row with a unique identifier using Angular and Bootstrap?

Currently handling Angular and Bootstrap in my work, but facing challenges with table manipulation and collapsing rows. I fetch data from a database and showcase it in a dynamically generated table using *ngFor and two rows within an ng-container. My goal ...

Typescript: Extracting data from enum items using types

I am facing a challenge with an enum type called Currency. I am unable to modify it because it is automatically generated in a graphql schema. However, I need to utilize it for my data but I'm unsure of how to go about doing so. enum Currency { rub ...

TSLint warning: Duplicate identifier detected - 'err'

Currently facing an issue with tslint displaying the following error Shadowed name: 'err' Providing the code snippet for reference fs.readdir(fileUrl, (err, files) => { fs.readFile(path.join(fileUrl, files[0]), function (err, data) ...

When working with an observable in an Angular Material table, the *ngIf directive may not function as expected

Attempting to utilize an Angular Material table with expandable rows, specifically to display information based on screen width reaching a particular breakpoint. Utilizing an observable isHandSetPortrait$ that is subscribed to in the HTML to determine if t ...

What's preventing me from using just one comparison condition in TypeScript?

The issue at hand is quite simple: An error occurred because I tried to compare a number with a 'Ref<number>' object. It seems ridiculous that I can't compare two numbers, but as I am new to Typescript, I would greatly appreciate some ...