Trouble encountered when implementing multiple conditions for checkboxes in an Angular 8 application

In my form, there are four checkboxes (3 for options and 1 for setting a plan) which have specific requirements:

  1. If all three options are checked, the set plan checkbox is automatically checked and the options disappear
  2. If the set plan checkbox is checked, the other options are also checked automatically, and then disappear
  3. If the set plan checkbox is unchecked, the other options reappear and are unchecked as well

While my code works fine for scenarios 1 and 2 leading to requirement 3, there seems to be an issue with scenario 1 not functioning properly when the set plan checkbox is unchecked. What could be missing in my code? Any advice would be appreciated.

Here's a simple Stackblitz illustrating the problem along with the source code provided.

(The actual code includes animations, so it's important that all options are checked before disappearing as per requirement 2)

HTML

<div [ngClass]="setClass()">
<div class="option">Option One
<input type="checkbox" [(ngModel)]="opt01" [checked]="setplan"/>
</div><br />
<div class="option">Option Two
<input type="checkbox" [(ngModel)]="opt02" [checked]="setplan"/>
</div><br />
<div class="option">Option There
<input type="checkbox" [(ngModel)]="opt03" [checked]="setplan"/>
</div>
</div><br>

<div style="background-color: lightgreen; width: 50%">Set Plan
<input type="checkbox"  [(ngModel)]="setplan" [checked]="opt01 && opt02 && opt03"/>
</div>

TS

public opt01: boolean;
public opt02: boolean;
public opt03: boolean;

public setplan: boolean;

setClass() {
  if (
    (this.opt01 == true &&
      this.opt02 == true &&
      this.opt03 == true) ||
    this.setplan == true
  ) {
    return 'container-wrap -hidden';
  } else if (this.setplan == false) {
    return 'container-wrap';
  }
} 

CSS (not critical)

.container-wrap {
  height: 120px;
  position: relative;
  overflow-y: hidden;
}
.container-wrap.-hidden {
  height: 0px;
  position: relative;
}
.option {
  background-color: lightgray; 
  width: 50%
}

Answer №1

Why go through so much trouble? Using the *ngIf directive is probably the simplest solution.

Give this a try: for the component's HTML:

<div *ngIf="!setPlan" class="container-wrap">
<div class="option">Option One
<input type="checkbox" [(ngModel)]="opt01" [checked]="setplan"/>
</div><br />
<div class="option">Option Two
<input type="checkbox" [(ngModel)]="opt02" [checked]="setplan"/>
</div><br />
<div class="option">Option Three
<input type="checkbox" [(ngModel)]="opt03" [checked]="setplan"/>
</div>
</div><br>

<div style="background-color: lightgreen; width: 50%">Set Plan
<input type="checkbox"  [(ngModel)]="setplan" [checked]="opt01 && opt02 && opt03"/>
</div>

No need for a setClass() function anymore. Your code will be cleaner without any extra classes. You can also add animations to Angular components templates that use the *ngIf directive. Check out an example blog here.

Answer №2

To handle the change event for your setplan input element, you can use ngModelchange.

`<div style="background-color: lightgreen; width: 50%">Set Plan
 <input type="checkbox"  [(ngModel)]="setplan" [checked]="opt01 && opt02 && opt03" 
         (ngModelChange)="changePlan($event)"/>
 </div>`

Next, create a method in your ts file named changePlan(event)

changePlan(event) {
 if (!event) {
  this.opt01 = false;
  this.opt02 = false;
  this.opt03 = false;
 } else {
  this.opt01 = this.opt02 = this.opt03 = true;
 }
}

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

Angular2 app hosted on firebase displaying an empty page

After developing an angular2 app, I followed the procedure for Firebase hosting. However, when I try to access my app, it is showing a default page instead. I would appreciate any help or guidance on this issue. https://i.sstatic.net/59aq7.png ...

Any tips on making Angular 8's sort table function seamlessly integrate with data retrieved from Firebase?

I am currently working on an angular PWA project that utilizes a material table to display data from Firebase. The data is being shown properly and the paginator is functioning as expected. However, I am facing an issue with sorting the data using mat-sort ...

The automatic filtering feature does not kick in when the sorting is changed

I've been working on an app that features a video database, allowing users to filter videos by category and sort them by rating. https://i.sstatic.net/cESZT.png Currently, the filtering system works fine once the options are changed. However, there ...

Incorporating an external TypeScript script into JavaScript

If I have a TypeScript file named test.ts containing the code below: private method(){ //some operations } How can I access the "method" function within a JavaScript file? ...

Is there a variance in window.innerWidth between Chrome and Firefox?

body, html { position:absolute; width:100%; height:100%; margin: 0; padding: 0; overflow: hidden; } When using window.innerWidth, there is a discrepancy between the values returned by Firefox and Chrome. Firefox return ...

What is the best way to maintain a fixed header for a content div?

I recently developed a website using angularjs. <html> <head></head> <body ng-app="app1" ng-controller = "ctrl1"> <header></header> <div ng-view></div> <footer></footer> </body> </ht ...

Updating Elements in an Array Using JavaScript is Not Functioning as Expected

In my Angular application, I have included some lines of TypeScript code which involve Boolean variables in the constructor and an array of objects. Each object in this array contains input variables. selftest: boolean; failed: boolean; locoStateItem ...

Tips for switching back and forth between two classes using jQuery?

I'm having some trouble with the toggleClass function. It doesn't seem to be working correctly for me. The image should toggle between displaying and hiding, but it only changes to hide, not back again. You can view my example here, along with t ...

The Carousel feature functions properly with 3 or more slides, but malfunctions when there are only 2 slides present

After implementing a minimal carousel, I discovered that it functions perfectly with 3 or more slides. However, as soon as I remove some slides, issues start to arise. Some of the problems I encountered include: The sliding animation is removed on ' ...

What causes the string to be treated as an object in React Native?

I am fetching a string value through an API and I need to display it in the View. However, the string value is coming as a Promise. How can I handle this? "Invariant Violation: Objects are not valid as a React child (found: object with keys {_40, _65 ...

Anglar2-useful-swiper does not automatically advance slides

I've been working on integrating the angular2-useful-swiper plugin into a single page application for image display, complete with auto rotation. However, I'm encountering an issue where the images are not transitioning as they should, and instea ...

Why aren't special methods/mixins for Sequelize associations being generated?

According to the documentation available at https://sequelize.org/docs/v6/core-concepts/assocs/#special-methodsmixins-added-to-instances: When establishing an association between two models, special methods are introduced that enable instances of those mo ...

Utilize the fetch function within a React functional component

I have been experimenting with different methods to fetch data only once before rendering, but I am encountering some challenges: It is not possible to call dispatch in componentDidMount as there is a restriction that it can only be done in Functional c ...

Difficulty retrieving information using AngularJS service post selection of item

Currently, I am working on a project involving an AngularJS application. While using the service testPanelService, I encountered a problem where selecting an item from a list correctly logs the details of the selected item. However, when attempting to fetc ...

Issue with CSS: Hover effect causing unexpected additional white space

My main goal is to implement a hover effect that covers an entire section, but I'm facing some challenges. When I hover over my products, it doesn't behave as expected and adds extra white space below while not covering the section properly. Thi ...

Revamp the Side Navigation Feature to Identify the Currently Viewed Section of the Page

My website currently features a side navigation bar that dynamically updates based on the user's scroll position. When the user reaches a specific height, a class is added to a div in the sidebar, turning it orange and indicating which part of the pag ...

Switch themes on the fly using Angular 2 and Meteor

I have a web application built with Meteor and Angular 2. I would like to implement a feature that allows users to change the theme by selecting one of two options: <select onChange="changeTheme()"> <option value="blue"> Blue</option> &l ...

Reset hover effect upon exiting the current website

Hey there! I am currently dealing with an interesting situation regarding a link styled as a button on my website. <a href="http://externalsite" class="button" target="_blank">go to external site</a> Additionally, I have applied a hover effec ...

Pass the parameter name to the controller using the Change function in Angular 2

When creating a string from multiple inputs, I have a requirement to include the name of the input element as the second parameter in a function. <input [(ngModel)]="programSearched" name="programSearched"(ngModelChange)="stringBuilderOnChangeMaker(pro ...

Creating a test scenario for displaying a list of posts

I am currently working on writing a test for the code snippet below, which essentially displays all blog posts with the most recent post appearing at the top. I am fairly new to React Testing Library and each time I try to include my components in the test ...