"Enable the Angular Material checkbox with the value set to checked

Check out my TypeScript code below:

import {Component} from '@angular/core';

@Component({
  selector: 'checkbox-configuration-example',
  templateUrl: 'checkbox-configuration-example.html',
  styleUrls: ['checkbox-configuration-example.css'],
})
export class CheckboxConfigurationExample {
  checked = false;
  indeterminate = false;
  align = 'start';
  disabled = false;

  items = [{selected: true, label: 'First Item'}, {selected: false, label: 'Second Item'}];
}

Here is the corresponding HTML code:

<mat-card>
  <mat-card-content>
    <h2 class="example-h2">Checkbox configuration</h2>

    <section class="example-section">
      <mat-checkbox class="example-margin" [(ngModel)]="checked">Items</mat-checkbox>
    </section>

    <h2 class="example-h2">Result</h2>

    <section class="example-section" *ngFor="let item of items">
      <mat-checkbox  class="example-margin" [(ngModel)]="checked">{{item.label}}</mat-checkbox>
    </section>


  </mat-card-content>
</mat-card>

And here is the CSS code:

.example-h2 {
  margin: 10px;
}

.example-section {
  display: flex;
  align-content: center;
  align-items: center;
  height: 60px;
}

.example-margin {
  margin: 0 10px;
}

In addition to the conditions mentioned in the code, we need to implement the following behaviors:

  1. If either 'First Item' or 'Second Item' is selected, the 'Items' checkbox should also be checked. However, if 'First Item' is selected, the status of 'Second Item' should remain unchanged and vice versa.
  2. If both 'First Item' and 'Second Item' checkboxes are unchecked, the 'Items' checkbox should also be unchecked.

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

Answer №1

To improve functionality, it is recommended to implement two distinct methods: onCheckedItem and onCheckedResult. In the onCheckedItem method, every item's selected value should be set to the checked value (either true or false based on the checkbox status). The onCheckedResult method creates an array to store the items' selected values. If the selectedArray contains true, the checkbox will be set as true; otherwise, it will be set as false.

import {Component, OnInit} from '@angular/core';
....
export class CheckboxConfigurableExample implements OnInit{
  checked: boolean = false;

  items = [
   {selected: true, label: 'First Item'}, 
   {selected: false, label: 'Second Item'}
  ];

  ngOnInit(): void {
    this.onCheckedResult();
  }

  onCheckedItem() {
    this.items.forEach((item) => {
      item.selected = this.checked
    });
  }

  onCheckedResult() {
    let selectedArray = [];
    this.items.forEach((item) => {
      selectedArray.push(item.selected)
    });
    selectedArray.includes(true) ? this.checked = true : this.checked = false;
  }
}

For seamless integration, make sure to include the ngOnInit lifecycle hook if you initially have items.selected set to true in your object.

When setting up your template, remember to assign a change event to each checkbox like the example below:

<h3>Checkbox configuration</h3>
<mat-checkbox (change)="onCheckedItem()" [(ngModel)]="checked"> Item</mat-checkbox>
<h3>Results</h3>
<ng-container *ngFor="let item of items">
  <mat-checkbox (change)="onCheckedResult()" [(ngModel)]="item.selected" class="chk-box"> 
    {{ item.label }}
  </mat-checkbox>
</ng-container>

Stay tuned for further updates!

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

A single click is required for Observables to load on an HTML page

While working on my Angular web application, I encountered an issue with displaying data when using Observables and Subjects. Typically, when searching the Firebase DB, I use *ngFor="let myvar of _myvar | async" in my HTML to display the retrieve ...

The intricate field name of a TypeScript class

I have a TypeScript class that looks like this - export class News { title: string; snapshot: string; headerImage: string; } In my Angular service, I have a method that retrieves a list of news in the following way - private searchNews(sor ...

Tips for converting API data to DTO (Data Transfer Object) using TypeScript

Here is an array of vehicles with their details. export const fetchDataFromApi = () => { return [ { vehicleId: 1, vehicleType: 'car', seats: 4, wheelType: 'summer', updatedAt: new Date().toISOString }, { vehicleId: 2, vehic ...

The TN-Models-FP error message states that it is not allowed to use the `create` model without an associated `entity` model

Utilizing the TN-models-fp library to construct a basic api inspired by the provided examples, here is my implementation in api.ts: import { axios } from '../axios-instance' import { createApi } from '@thinknimble/tn-models-fp' import { ...

Is it possible to use Immutable named parameters with defaults in Typescript during compilation?

Here is an example that highlights the question, but unfortunately it does not function as intended: function test({ name = 'Bob', age = 18 }: { readonly name?: string, readonly age?: number }) { // this should result in an error (but doesn&apo ...

"Exploring AngularFire Database: Simple ways to retrieve the total number of items in a list

I attempted to utilize angularfire2 in order to develop a function that retrieves the total number of entries in a list within a firebase real-time database. For instance: Retrieve the count of users in '/users'. I am not interested in continuou ...

Angular - optimizing performance with efficient HTTP response caching tactics

I'm managing numerous services that make requests to a REST service, and I'm looking for the optimal method to cache the data obtained from the server for future use. Can someone advise on the most effective way to store response data? ...

Having trouble syncing ionic and capacitor - npm keeps throwing an error

In my blank Ionic project, I am attempting to integrate Capacitor with Ionic in order to build an Android app. When I run the following command: ionic capacitor add android, I encounter an npm error. Can someone please assist me in resolving this issue? C ...

Ways to indicate in Typescript that a value, if it exists, is not undefined

Is there a way to represent the following logic in TypeScript? type LanguageName = "javascript" | "typescript" | "java" | "csharp" type LanguageToWasmMap = { [key in LanguageName]: Exclude<LanguageName, key> ...

Unable to locate the API compiler-cli and the VERSION function

After downloading a repository from GitHub to run an Angular project, I typically use the command npm install to add node modules to the project. However, when I then attempt to run ng serve, I encounter the following error: https://i.stack.imgur.com/xiqo ...

Can you identify the reason for the hydration issue in my next.js project?

My ThreadCard.tsx component contains a LikeButton.tsx component, and the liked state of LikeButton.tsx should be unique for each logged-in user. I have successfully implemented the thread liking functionality in my app, but I encountered a hydration error, ...

Implementing optional default values in React props using conditional types

I have a dilemma with conditional props types When attempting to set a default value for my optional prop within the conditional type, it causes issues with the types export type ChatBase = { id: string; title: string; } type ChatCardProps = { title: ...

tips for concealing a row in the mui data grid

I am working on a data grid using MUI and I have a specific requirement to hide certain rows based on a condition in one of the columns. The issue is that while there are props available for hiding columns, such as hide there doesn't seem to be an eq ...

The concept of TypeScript usage within the `mui-x` DataGrid while calling the `useGridApiRef()` function

Could someone please help me understand the syntax used in this code snippet from mui/mui-x? export declare const useGridApiRef: <Api extends GridApiCommon = GridApiPro>() => React.MutableRefObject<Api>; My interpretation is that it exports ...

What is the process of declaring a global function in TypeScript?

I am looking to create a universal function that can be accessed globally without needing to import the module each time it is used. The purpose of this function is to serve as an alternative to the safe navigation operator (?) found in C#. I want to avoi ...

How can I stop the SvelteKit production node server from filling up the logs with "Error: not found /path/here"?

After developing a website using sveltekit, I decided to build it for production as a nodejs server and deploy it on my linux server with Caddy as a reverse proxy. Unexpectedly, upon starting the server, I began receiving error messages in the log such as ...

Sharing Properties Across Angular Components using TypeScript

Seeking a solution for storing properties needed in multiple components using a config file. For example: number-one-component.ts export class NumberOneComponent { view: any[]; xAxis: number; yAxis: number; label: string; labelPositio ...

Angular 4's unique feature is the ability to incorporate multiple date pickers without the

Is there a way to implement a multiple date picker using Angular 4 and TypeScript only? I came across one solution but it seems to only support Angular 1. Thank you in advance! ...

Verify that each interface in an array includes all of its respective fields - Angular 8

I've recently created a collection of typed interfaces, each with optional fields. I'm wondering if there is an efficient method to verify that all interfaces in the array have their fields filled. Here's the interface I'm working wit ...

When using the map function, I am receiving an empty item instead of the intended item based on a condition

Need assistance with my Reducer in ngRx. I am trying to create a single item from an item matching an if condition, but only getting an empty item. Can someone please help me out? This is the code for the Reducer: on(rawSignalsActions.changeRangeSchema, ...