When using the Angular checkbox, remember to keep one box checked at all times

When my page loads, there are two checkboxes: Active and InActive. By default, both are checked (true) and the user has the ability to uncheck either one, but not both at the same time.

To handle this situation, I implemented a getter method to retrieve the checkbox values and a method call to validate any changes made.

My TypeScript code:

import { Component, OnInit, ChangeDetectionStrategy } from '@angular/core';

@Component({
  selector: 'app-actions-filter',
  templateUrl: './actions-filter.component.html',
  styleUrls: ['./actions-filter.component.css'],
  changeDetection: ChangeDetectionStrategy.OnPush
})

export class ActionsFilterComponent implements OnInit {
  private _isActive: boolean = true;
  get isActive(): boolean {
    return this._isActive;
  }

  setActive(value: boolean) {
    if (this._isInActive === false && value === false) {
      this._isActive = true;
      return;
    }
    this._isActive = value;
  }

  private _isInActive: boolean = true;
  get isInActive(): boolean {
    return this._isInactive;
  }

  setInActive(value: boolean) {
    if (this._isActive === false && value === false) {
      this._isInActive = true;
      return;
    }
    this._isInActive = value;
  }

  constructor() {}

  ngOnInit() {}
}

And here is my HTML:

<div class="app-filter-block">
  <div class="btn-group">
    <div class="checkbox btn">
      <input type="checkbox" id="btn-action-active" (change)='setActive($event.target.checked)' [checked]="isActive" />
      <label for="btn-action-active"> Active </label>
    </div>
    <div class="checkbox btn">
      <input type="checkbox" id="btn-action-inactive" (change)='setInActive($event.target.checked)'
        [checked]='isInActive' />
      <label for="btn-action-inactive"> Inactive </label>
    </div>
  </div>
</div>

Additionally, the checkboxes are styled using Clarity UI components. More information can be found here.

Answer №1

If the first checkbox is left unchecked, you may consider deactivating the second checkbox as well.

<div class="app-filter-block">
  <div class="btn-group">
    <div class="checkbox btn">
      <input type="checkbox" id="btn-action-active" 
      (change)='setActive($event.target.checked)' 
      [disabled]="!isInActive"
      [checked]="isActive" />
      <label for="btn-action-active">Active</label>
    </div>
    <div class="checkbox btn">
      <input type="checkbox" id="btn-action-inactive" 
      (change)='setInActive($event.target.checked)'
      [disabled]="!isActive"
      [checked]='isInActive' />
      <label for="btn-action-inactive">Inactive</label>
    </div>
  </div>
</div>

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

Can a feature be implemented in Angular 2 to execute a command when a file is saved?

Having some trouble setting up SCSS-lint on an Angular 2 project. I can get it to work with npm start and when running the command manually, but I can't quite figure out how to get it to run when I save a file. "scripts": { "ng": "ng", "sta ...

Tips for setting focus on an input field within a Clarity modalHere are some steps

Currently, I am working with Clarity 3 and Angular 9. In my project, there is a Modal window that contains only one input field. The requirement is that when the modal pops up, the input field should automatically be in a focused state. Below is the code ...

What is the best way to implement a dynamic back button in Next.js?

Being familiar with creating a standard back button, I am now eager to craft one that directs the user back by one step in the URL rather than returning to the previous page. This way, I can utilize the button in various locations without needing to alter ...

Can an Angular application be developed without the use of the app-root tag in the index.html file?

I'm a newcomer to Angular and I'm trying to wrap my head around how it functions. For example, if I have a component named "login", how can I make Angular render it directly? When I try to replace the app-root tag with app-login in index.html, n ...

The error message "Angular 4 does not recognize the 'dragula' property as a valid property of the 'div' element" is displayed

Struggling to integrate ng2-dragula with the AspNetCore SPA template. Despite trying various solutions, I am still encountering the following error: Exception: Call to Node module failed with error: Error: Template parse errors: Can't bind to 'd ...

Unlimited Webpack watching cycle - tips on disregarding modifications in .js files, and more

There seems to be an issue with my webpack -w command when using ts-loader, as it is stuck in an endless loop. It appears that the problem arises because webpack -w detects changes in .js files, resulting in a continuous cycle: webpack -w => ts trans ...

Steps for Loading HTML5 Video Element in Ionic 2

Struggling to showcase a list of videos from my server, here's the issue I'm encountering and the layout of the app. https://i.stack.imgur.com/HWVt3.png This is the code snippet in HTML: <ion-list> <button ion-item *ngFor="let v ...

How can I transfer data to a different component in Angular 11 that is not directly related?

Within the home component, there is a line that reads ...<app-root [message]="hii"> which opens the app-root component. The app-root component has an @input and {{message}} in the HTML is functioning properly. However, instead of opening t ...

When using Jest + Enzyme to test a stateful class component, encountering problems with Material-UI's withStyles functionality is a common issue

I have a React + TypeScript application with server-side rendering (SSR). I am using Material-UI and following the SSR instructions provided here. Most of my components are stateful, and I test them using Jest + Enzyme. Below is an example of one such com ...

Why won't the sound play on the button with the picture?

I am currently working on a website project that requires buttons with pictures and sound. Despite my efforts, the sound feature is not functioning properly in Chrome and Firefox. I am still learning and would like to know how to toggle the sound on and of ...

The child object in Typescript is characterized by its strong typing system

Looking to convert plain AngularJS code to Typescript? Take a look at this example: app.someController = function ($scope) { // var $scope.Data = null; var $scope.Data: SomeCollection = null; I need to associate Data with scope and specify it as type ...

Tips for configuring the cookie expiration date using the ngx-cookie-service library

Can anyone offer assistance with setting the expire date for cookies in my Angular 5 app using ngx-cookie-service? Here is what I have tried: setCookies($event){ this.cookieService.set( 'retailAppCookies', "true", 30 ); this.cook ...

How can I validate a method for formGroup in Angular 2?

Below is a form I am working with: this.changePasswordForm = this.formBuilder.group({ 'passwordNew': ['', ValidationService.passwordValidator], matchingPasswords('passwordNew', 'passwordNewConfirmation')(this) ...

Resetting Values in an Angular Reactive FormArray

Encountered an unusual bug while working with Angular reactive forms. I have set up a FormArray to manage a dynamic form where fields can be added or removed. My goal is to reset the form to its original state, including the values and number of form input ...

The lite-server is unable to find an override file named `bs-config.json` or `bs-config.js`

I've been working on running my first Angular 2 app. I carefully followed the steps provided by angular2. However, upon running the command npm start, I encountered the following error in the terminal: No bs-config.json or bs-config.js override fil ...

The dynamic concatenation of Tailwind classes is failing to have any effect, even though the full class name is being

I'm currently using Tailwind CSS within my Next.js project and I have a common method that dynamically returns the desired background color. However, despite adding the full class name, the background color is not displaying as expected. After reading ...

Generate a custom string to reference a JSON object containing a variable from an Angular HTML document

I am trying to generate a string within my HTML file to access data from a JSON object. HTML File <app-banner></app-banner> <section id="mail-view" class="bg-gray" > <div class="container"> <figure id="state-stats" class= ...

Webpack is failing to recognize certain CSS files

My development stack includes Vue.js 2.5.15, Webpack 4.12.0, css-loader 0.28.11, ASP.Net Core 2.1 in Visual Studio 2017. Starting with the Visual Studio asp.net core template project for Vue and Typescript, I prefer to have individual small CSS files with ...

We encountered a surprising character "EOF" in the code. Could it be due to an unescaped "{" in the template? Please use "{{ '{' }}" to properly escape it

I encountered an issue while upgrading my angular 2 app from beta 9 to RC5. The error I received is in my form template. Below is the detailed error: zone.js:461 Unhandled Promise rejection: Template parse errors: Unexpected character "EOF" (D ...

Angular2 and the complexity of deeply nested JSON

As a newcomer to Angular2, I am struggling to figure out how to display my JSON data using Angular2. Here is the JSON data I am working with: { "logoEditorData":{ "logo":{ "companyNameOption":{ "fontSize":{ "c ...