Fails to update the ngModel linked to the checkbox

<label class="checkiconImg bg-white">
    <input type="checkbox"
           [(ngModel)]="quoteSupplierCover.isShowInComparisonTool"
            />
    <span class="geekmark ShowInComparisonToolCheckBox"
          pTooltip="Please deselect this before you select other."
          tooltipEvent="hover"
          (click)="checkRemark(coverIndex, roundIndex)"
          [tooltipDisabled]="!quoteSupplierCover.showWarningToolTip"></span>
</label>

This checkbox allows users to choose whether or not the remarks provided in the input (not shown here) should be displayed in a separate comparison tool. Before enabling this feature, we need to ensure that no other rounds have a checked review. In such cases, the user must uncheck those and check the current one they wish to display. The issue arises when !hasComparisonToolSet evaluates to true, as it does not update isShowInComparisonTool to true, causing the checkbox and geekmark to remain green.

checkRemark(quoteSupplierIndex, roundIndex) {
    if (this.negotiationRounds[roundIndex] && this.negotiationRounds[roundIndex][1].quoteCoverageAssessments[quoteSupplierIndex]) {
        try {
            this.negotiationRounds[roundIndex][1].quoteCoverageAssessments[quoteSupplierIndex].isShowInComparisonTool = false;
        } finally {
            // Check other rounds for any that have the comparison tool set
            const hasComparisonToolSet = this.negotiationRounds
                .filter((_, idx) => idx !== roundIndex)
                .some(round => {
                    const isShowInComparisonTool = round[1].quoteCoverageAssessments[quoteSupplierIndex]?.isShowInComparisonTool === true;
                    if (isShowInComparisonTool) {
                        round[1].quoteCoverageAssessments[quoteSupplierIndex].showWarningToolTip = true;
                    }
                    return isShowInComparisonTool;
                });
            if (!hasComparisonToolSet) {
                // Reset values if no other round has it set
                console.log("No other rounds with comparison tool set, resetting values.");
                const assessment = this.negotiationRounds[roundIndex][1].quoteCoverageAssessments[quoteSupplierIndex];
                assessment.isShowInComparisonTool = true;
                assessment.showWarningToolTip = false;

                if (assessment.remarks !== null && assessment.isShowInComparisonTool === true && assessment.remarksType === 0) {
                    this.showRemark = true;
                }
            } 
        }       
    }        
}

Attempted to add

(ngModelChange)="checkRemark(coverIndex, roundIndex)"
directly to the checkbox like this:

<label class="checkiconImg bg-white">
    <input type="checkbox"
           [(ngModel)]="quoteSupplierCover.isShowInComparisonTool"
           (ngModelChange)="checkRemark(coverIndex, roundIndex)" />
    <span class="geekmark ShowInComparisonToolCheckBox"
           pTooltip="Please deselect this before you select other."
           tooltipEvent="hover"
           [tooltipDisabled]="!quoteSupplierCover.showWarningToolTip"></span>
</label>

However, despite updating the model, the checkbox remained checked even though quoteSupplierCover.isShowInComparisonTool was false for that particular case.

Answer №1

It seems like the issue you're facing is related to the template not detecting changes accurately or possibly updating the wrong index.

To resolve this, you can try the following steps:

  • Make sure you are updating the correct index in the array. If so, then:

  • Try reassigning the same variable to trigger the change detection mechanism like this:

    this.negotiationRounds[roundIndex][1].quoteCoverageAssessments[quoteSupplierIndex] = {...assesment}

    Alternatively, you can manually trigger the change detection mechanism by importing the changeDetectorRef and calling the detectChanges method:

    this.changeDetectorRef.detectChanges();

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

Encountering the error message: "Unable to access the 'valid' property of an undefined object in Angular 5 template form"

I want to build a Model-Driven Angular template for registering new users. I've set up two main files for this: admin-register.component.html admin-register-form.component.ts However, when I try to access the page with the registration form, I encou ...

Unable to locate the last form control with the specified name

I have a project that involves displaying images on our NAS using Angular 17. On the main page, I have 3 mat-form-fields. Strangely, when I add the last mat-form-field, I encounter the following error - ERROR Error: Cannot find control with name: 'num ...

Issues with loading NextJS/Ant-design styles and JS bundles are causing delays in the staging environment

Hey there lovely folks, I'm in need of assistance with my NextJS and Ant-design application. The current issue is only occurring on the stagging & production environment, I am unable to replicate it locally, even by running: npm run dev or npm r ...

What happens when the loading state does not update while using an async function in an onClick event?

I'm currently working on implementing the MUI Loading Button and encountering an issue with changing the loading state of the button upon click. Despite setting the state of downloadLoading to true in the onClick event, it always returns false. The p ...

Is there a way to prevent an undefined legend from being automatically created in an ng 2 chart during the loading process?

While working with the ng-2 chart, I noticed that an undefined legend is automatically generated in the stacked bar chart with a color that I did not specify. I am using a specific set of colors defined in an array. Is there a way to remove only the undefi ...

Issue with Angular: event.key doesn't register as shft+tab when pressing Shift+Tab key

Our website features a dropdown menu that can be opened and closed by clicking, revealing a list of li items. However, we are currently experiencing an issue with keyboard focus navigation. When the Tab key is pressed, the focus properly moves from one li ...

Failing to complete a field in the form does not generate an error message when submitted [AngularJS]

My code is designed to display an error message if the user clicks the submit button without filling in a field. However, the functionality is currently not working as intended. <form name="loginForm" ng-submit="loginForm.$valid && login()" n ...

Is there a way to circumvent the mouse up event?

I want to create a feature where when a user clicks down, something specific occurs. The sequence of events includes: An action taking place (which is not the focus here). Triggering a mouse up event. Implemented with: angular, html, css. Excludes: jQue ...

What are some methods for utilizing spring security Ldap to authenticate with angularjs on the client side?

Recently, I developed a web application using spring-mvc and angularjs. Initially, I implemented authentication by storing user credentials in a database table. However, I now have a requirement to switch to LDAP for authentication. Can anyone provide guid ...

How to Iterate Over Nested Objects in AngularJS Using a forEach Loop

As a newcomer to AngularJS, I am eager to delve deeper into working with JSON objects that contain nested objects and arrays. The simplified version I am currently working with is a great starting point to gain a basic understanding and eventually tackle m ...

Angular view showcasing a JSON array

After retrieving data from the Laravel API, I used the following method: this.dataService.getData().subscribe(res=>{ this.contacts=res }); Upon receiving a JSON array response from Laravel like the one below, I attempted to iterate throu ...

Incorporate dots and decimals into integers using AngularJS

Given an integer such as 12345, I am looking to implement a straightforward AngularJS filter to display it with two decimal places: 123.45 Update: Many thanks to @benohead for providing the solution: {{val/100 | number:2}} ...

Troubleshooting modifications not functioning

Currently, I have implemented a dropdown similar to the one shown below: <select class="form-control" data-ng-model="vm.priceBuilder.projectID" data-ng-change="vm.c ...

Exploring Angular 17 SSR: How to Determine if Component Output Event is Subscribed

Developing a toolbar component with an action button in Angular 17 SSR. The button is a generic one, and I am attempting to determine if the component output events are being observed to determine which buttons are displayed. Is the code below valid? < ...

Just recently updated to Angular 14 and I'm encountering a problem with images not loading from the assets folder. I'm wondering if there is a configuration step I missed. Could someone please

https://i.stack.imgur.com/4LEQ4.png https://i.stack.imgur.com/3sxzF.png Is there a configuration missing in Angular 14? When I try using <img [src]="assets/images/sidebarNav"> with ./, ../, it doesn't work. I have followed the instr ...

What is the best way to apply styling to the placeholder of an input element using Angular?

Is there a way to achieve something similar in Angular? [style.placeholder.color]="active ? 'white' : 'grey'" I'm looking to bind the placeholder pseudo element of an input element. How can I bind it to the style propert ...

How to Delete an Item from an Array in BehaviorSubject Using Angular/Typescript

I have encountered an issue while trying to delete a specific element from my array upon user click. Instead of removing the intended item only, it deletes all elements in the array. I attempted to use splice method on the dataService object, but I'm ...

No invocation of 'invokeMiddleware' was suggested

Encountered this specific issue when setting up loopback4 authentication. constructor ( // ---- INSERT THIS LINE ------ @inject(AuthenticationBindings.AUTH_ACTION) protected authenticateRequest: AuthenticateFn, ) { super(authen ...

Tips for adjusting the dimensions of a child element to match its parent in Angular 12 with Typescript

I have included the child component in the parent component and I am displaying that child component within a col-md-8. What I want to achieve is to highlight a specific div in the child component with additional text, making it equal in size to the parent ...

Optimal Procedure for New Users Form (Jade / Angular) in HTML

I'm currently working on integrating a form into my app for users to create tasks. This form should only appear the first time a user attempts to create a task. As someone who is not very experienced with frontend development, I find myself wondering ...