Discover a method to deselect a checkbox within a separate component in angular15

I am currently dealing with Angular15 and I find myself stuck on an issue related to checkbox selection change.

Situation: As per the requirements, I have a menu bar and a Checkbox. The Checkbox is generated from a reusable component which is used in the Menu bar page. Initially, the checkbox is checked. However, when I alter the menu bar options, the checkbox should be unchecked.

Challenge: In the "Display" page mentioned above, the checkbox is initially checked. I wish to uncheck the checkbox by modifying the menu options. If I select "User", the checkbox should become unchecked. Every time the menu options are changed, the checkbox should reset to an unchecked state if it was previously checked.

selectionpage.component.html

<p>Checkbox Selection!</p>

<input type="checkbox" [(ngModel)]="isChecked">Select All

A checkbox has been added with the input parameter "isChecked".

selectionpage.component.ts

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

@Component({
  selector: 'app-selectionpage',
  templateUrl: './selectionpage.component.html',
  styleUrls: ['./selectionpage.component.scss']
})
export class SelectionpageComponent {
@Input() isChecked:boolean=true;
}

Now I will utilize this "Selectionpage" within the "displaypage" to include the checkbox.

display-page.component.html

<div class="tab-menu-container">
  <div class="tab-menu-wrapper">
    <ng-container *ngFor="let selectvalue of selectionContent">
      <div class="tab">
        <span (click)="changerArchiveType()" style="cursor: pointer;">{{ selectvalue }}</span>|
      </div>
    </ng-container>
  </div>
</div>
<app-selectionpage [isChecked]="SelectionChange"></app-selectionpage>

display-page.component.scss

.tab-menu-container{
    height: 56px;
    display:flex;
    justify-content: center;
    background: #f2f2f2;
    .tab-menu-wrapper{
        width: 85%;
        display: flex;
        flex-wrap: wrap;
        column-gap: 2rem;
        padding-top: 20px;

        .tab{
            width: fit-content;
            font-weight: 700;
            font-size: 15px;
            line-height: 20px;
        }
    }
}

display-page.component.ts

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

@Component({
  selector: 'app-display-page',
  templateUrl: './display-page.component.html',
  styleUrls: ['./display-page.component.scss'],
})
export class DisplayPageComponent {
  public selectionContent: Array<string> = [
    'User',
    'Admin',
    'SuperAdmin',
    'Seller',
  ];
  public SelectionChange:boolean=false;
  changerArchiveType() {
    this.SelectionChange=false;
    console.log("Checked:",this.SelectionChange)
  }
}

The page now features a "Menu bar" with options and a checkbox.

If I modify the menu bar option, the checkbox should be cleared. It works correctly the first time after the page loads, but subsequent attempts to uncheck upon changing the menu do not function as intended.

Thank you

Answer №1

It's amazing that this functionality actually works. The issue lies in the fact that the SelectionChange property within the DisplayPageComponent never updates from its initial value of false.

To resolve this, you should trigger a change event whenever the checkbox is checked by utilizing an EventEmitter along with the Output decorator. It is recommended to name the output variable the same as the input one but with a Change suffix, enabling you to leverage two-way data binding similar to how you used the ngModel directive.

selectionpage.component.ts

Add the isCheckedChange event emitter.

export class SelectionpageComponent {
  @Input() isChecked: boolean = true;

  @Output() readonly isCheckedChange = new EventEmitter<boolean>();
}

selectionpage.component.html

Emit the isCheckedChange event when the ngModel changes.

<input type="checkbox" [(ngModel)]="isChecked" 
       (ngModelChange)="isCheckedChange.emit($event)">Select All

display-page.component.html

Implement two-way binding for isChecked in the parent component.

<app-selectionpage [(isChecked)]="SelectionChange"></app-selectionpage>

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

Typescript sometimes struggles to definitively determine whether a property is null or not

interface A { id?: string } interface B { id: string } function test(a: A, b: A) { if (!a.id && !b.id) { return } let c: B = { id: a.id || b.id } } Check out the code on playground An error arises stating that 'objectI ...

Angular List Selector: A versatile multiple selection component with a stylish list design

I'm in need of a select component similar to the one shown in The issue is that Material Angular doesn't have this specific component, so I opted to use the default HTML select inside my component. Everything was working fine until I tried to de ...

Encountering an error while compiling the Angular 8 app: "expected ':' but got error TS1005"

As I work on developing an Angular 8 application through a tutorial, I find myself facing a challenge in my header component. Specifically, I am looking to display the email address of the currently logged-in user within this component. The code snippet fr ...

The version of Angular CLI on my local machine is newer than the global

I have been trying to set up a new Angular project using Angular CLI version 13.3.10. However, every time I create a new project, it ends up being in version 13.3.11. Prior to creating this project, I followed the steps of running npm uninstall -g @angula ...

Steps for including a component in a loop using Angular 6

I'm working on a component that contains two input fields. The goal is to have a row pop up every time the user clicks on the add button, with all the inputs eventually being collected in an array of objects. For example, the component template looks ...

Navigate back to the main page using a tab

Is there a way to navigate back to the rootPage that is defined in the appComponent when using tabs? I have found that the setRoot method does not function as I anticipated. When used on a Tab page, the navigation stack is not cleared. Instead of the navig ...

"Implementing material-ui in Angular 7: A Step-by-Step Guide

I am looking to integrate material-ui into my Angular 7 project. While I know that Angular Material is available, I prefer using ui-material over it. However, I am unsure about how to implement ui-material in an Angular environment. ...

Issue with the height not being updated in a parent React nested Accordion

Currently, I am in the process of developing the mobile version of my homepage. However, there seems to be a bug in my nested accordion labeled "Projects." The bug is causing an issue where the bottom projects section does not display at the correct height ...

How to make an input blur in Angular 2 when a button is clicked?

Is there a way to blur an input field by pressing the return button on a mobile native keyboard? Here is an example: <input type="text" #search> this.search.blur() //-- unfocus and hide keyboard ...

Issue: Typescript/React module does not have any exported components

I'm currently facing an issue with exporting prop types from one view component to another container component and using them as state type definitions: // ./Component.tsx export type Props { someProp: string; } export const Component = (props: ...

The page fails to load when redirected, however, it briefly displays the page upon clicking the back button before navigating back to the previous page

Currently, I am working with Angular 2 and encountering an issue when attempting to click on a link. The loading bar continues to progress without displaying the data or HTML content on the page. Furthermore, if I try to go back to the previous page, the i ...

Issue with border radius in MUI 5 affecting table body and footer elements

Currently, I am diving into a new project utilizing React version 18.2 and MUI 5.10.3 library. My main task involves designing a table with specific styles within one of the components. The table header should not display any border lines. The table body ...

Creating a welcome screen that is displayed only the first time the app is opened

Within my application, I envisioned a startup/welcome page that users would encounter when the app is launched. They could then proceed by clicking a button to navigate to the login screen and continue using the app. Subsequently, each time the user revisi ...

Leveraging Angular App with the Bootstrap .modal() JQuery method

I'm encountering issues with Bootstrap 4 and NPM/Angular CLI when using the .modal methods Error: TypeError: $(...).modal is not a function Main.ts: import * as $ from 'jquery'; import * as bootstrap from 'bootstrap'; App.compo ...

Testing the open dialog with a unit test case

I encountered an issue while writing a unit test case for the open dialog feature in Angular 7. A TypeError is being thrown: "Cannot read property 'debugElement' of undefined." I am seeking assistance from anyone who can help me troubleshoot this ...

Adjust the control's value as you monitor any modifications

As I monitor the changes within a reactive form by subscribing to the value changes, I have encountered an issue where certain values unset in the form prevent the Angular Material Slide Toggle from toggling to false. This is crucial as it affects the "Act ...

Tips on expanding typings in TypeScript?

In my software library, there exists a map function with the following definitions: function map<T, U>(f: (x: T) => U, a: Array<T>): Array<U> function map<T, U>(f: (x: T) => U, a: Functor<T>): Functor<U> Furtherm ...

Refine specific unions by considering past values that have been used

Here's the scenario at hand: type Option = 'x' | 'y' | 'z' | 'w' type Inquiry = { query: string; choices: Option[]; defaultChoice: Option // here's where it gets tricky } I am looking to set the def ...

The functionality of the mat-radio-group is not rendered properly within an Angular formArray

Form elements that do not function properly with the formArray have been identified. Despite rendering, clicking on a button does not trigger any action. The editChoice() event fails to execute even when a break point is set in it. The controls also fail ...

What is the proper way to address the error message regarding requestAnimationFrame exceeding the permitted time limit?

My Angular application is quite complex and relies heavily on pure cesium. Upon startup, I am encountering numerous warnings such as: Violation ‘requestAnimationFrame’ handler took 742ms. Violation ‘load’ handler took 80ms. I attempted to resolve ...