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

When a form contains a ViewChild element, changes to the ViewChild element do not automatically mark the

Let's set the stage: MainComponent.html <form #someForm > <input type="text" name="title" [(ngModel)]="mainVar" /> <child-component /> <input type="submit" [disabled]="someForm.form.pristine" /> </form> ChildComp ...

Acquire Superheroes in Journey of Champions from a REST endpoint using Angular 2

Upon completing the Angular 2 Tour of heroes tutorial, I found myself pondering how to "retrieve the heroes" using a REST API. If my API is hosted at http://localhost:7000/heroes and returns a JSON list of "mock-heroes", what steps must I take to ensure a ...

step-by-step guide to leveraging the heatmap functionality of google maps with angular agm

For my current Angular 5 project, I am utilizing the angular component @agm/core found at https://github.com/SebastianM/angular-google-maps to display Google Maps. It's been working well so far, but now I'm looking to incorporate a heatmap layer ...

Is it possible to utilize an await in an rxjs observable?

Implementing an interceptor for my HTTP requests requires the use of the access token from the user instance. Within my app component, I initialize the user: app.component.ts private async restoreUser(): Promise<UserModel | any> { // ... some vi ...

Guide to publishing with Chromatic in a Storybook Angular NX workspace

Hey there, I'm looking for some help with running Storybook Chromatic in an NX workspace. My Angular application and libraries are functioning properly when served locally, and I've been able to run stories for my projects without any issues. I ...

What is the way to imitate a variable with Jasmine Spy?

Trying to troubleshoot a login feature, how can I mock everything except string variables? @Component({ selector: 'app-login', templateUrl: './login.component.html', styleUrls: ['./login.component.scss']) export c ...

How can I properly containerize an Express Gatsby application with Docker?

SOLUTION: I am currently working on a project involving an express-gatsby app that needs to be built and deployed using GitHub Actions. To deploy it on Heroku, I have learned that containerizing the app is necessary. As a result, I have created a Dockerfil ...

The Event Typing System

I am currently in the process of setting up a typed event system and have encountered an issue that I need help with: enum Event { ItemCreated = "item-created", UserUpdated = "user-updated", } export interface Events { [Event.Ite ...

Guide to transforming a TaskOption into a TaskEither with fp-ts

I have a method that can locate an item in the database and retrieve a TaskOption: find: (key: SchemaInfo) => TO.TaskOption<Schema> and another method to store it: register: (schema: Schema) => TE.TaskEither<Error, void> Within my regis ...

Navigating through nested routes in Angular 5

I recently started learning about Angular, and I could really use some guidance on routing. Here is my current setup. app.component.html <router-outlet name="nav"></router-outlet> <router-outlet name="left-sidebar"></router-outlet> ...

Issue resolved: Mysterious fix found for background images not displaying in NextJS React components

I am having trouble displaying a background image on an element in NextJs using Typescript and Tailwind. I do not believe it is a TypeScript issue since I am not receiving any errors or IntelliSense warnings. Below is the code I am working with: var classn ...

The global and centered positioning in @angular/cdk/overlay is not functioning as expected

I am currently experimenting with the new @angular/cdk library, but I am having trouble getting the position strategy to work. I simply want to display a modal that is centered on the screen with a backdrop. I know I can apply a class to the pane and use f ...

Prevent ASP.NET Core routing from intercepting Angular 5 routing calls during deep linking operations

I am currently utilizing ASP.NET Core MVC for managing API calls, with routing set to api/*. Additionally, Angular 5.x is being used alongside its own routing system. Everything functions smoothly when running locally (Core on port 5000 and Angular on 420 ...

Creating data types from the name of the route in vue-router route[x]

I am attempting to generate route names based on the routes defined in the Vue Router. My goal is to utilize a helper function called findRouteByName() to locate a specific route. However, I encountered an issue when trying to define the parameters of the ...

TypeScript does not throw a compiler error for incorrect type usage

In my current setup using Ionic 3 (Angular 5), I have noticed that specifying the type of a variable or function doesn't seem to have any impact on the functionality. It behaves just like it would in plain JavaScript, with no errors being generated. I ...

What is the process of incorporating a JavaScript node module into TypeScript?

Having trouble importing the xml2js module as I keep getting a 404 error stating that it's not found. import xml2js from 'xml2js'; Any suggestions on how to properly import JavaScript modules located in the node_modules directory when work ...

Troubleshooting: Angular version 4.3 Interceptor malfunctioning

I have been trying to implement new interceptors in Angular 4.3 to set the authorization header for all requests, but it doesn't seem to be working. I placed a breakpoint inside the interceptor's 'intercept' method, but the browser didn ...

Issue with *ngIf on Nativescript not functioning properly on iOS

I am encountering a major issue in my project. The *ngIf directive I am using is functioning only on the Android platform and not on iOS. Here is the HTML code snippet: <GridLayout columns ="auto, auto" rows="*" (tap)="open()"> <StackLayout co ...

Is there a way to adjust the width of a table cell in Material UI using React?

I encountered a problem where I am attempting to adjust the width of a table cell, specifically in Typescript. However, I am only able to choose between medium and small sizes for TableCellProps. Is there a workaround for this issue? I am looking to expand ...

What is the best way to transfer a property-handling function to a container?

One of the main classes in my codebase is the ParentComponent export class ParentComponent extends React.Component<IParentComponentProps, any> { constructor(props: IParentComponent Props) { super(props); this.state = { shouldResetFoc ...