The view fails to update when the object is modified

Within the acceptRequest function in child.component, the commissioner.requestAccepted property is set to false, and then the updated commissioner object is returned.

Ideally, I want the button to be automatically removed from the view once the object is updated, but currently, this isn't happening. I have to manually refresh the page for the button to disappear.

Snippet from parent.component.ts:

commissioners: any[];

ngOnInit() {
    this.usersService.getCommissioners().subscribe(
      res => {
        this.commissioners = res.commissioners;
      },
      err => {
        console.log(err);
      }
    )
  }

Snippet from parent.component.html:

<child-list *ngIf="commissioners" [commissioners]="commissioners"></child-list>

Snippet from child.component.ts:

  @Input() commissioners: any[];

  ngOnChanges(changes: SimpleChange) {
    this.commissioners = changes['commissioners'].currentValue;
  }

  acceptRequest(commissionerId) {
    this.usersService.acceptRequest(commissionerId)
      .subscribe(
        res => {
          for (let commissioner of this.commissioners) {
            if (commissioner._id == res._id) {
              console.log(commissioner); //old object (requestAccepted: false)
              commissioner = res;
              console.log(commissioner); //new object (requestAccepted: true)
              break;
            }
          }
        },
        err => {
          console.log(err);
        });
  }

Snippet from child.component.html:

<div *ngFor="let commissioner of commissioners">
   <button *ngIf="!commissioner.requestAccepted" class="btn btn-primary" (click)="acceptRequest(commissioner._id)">Accept</button>
</div>

Answer №1

It's possible that the if statement you're using is evaluating to false. However, this could actually be the key to resolving your issue. Consider using ===:

Also, keep in mind that you're only updating the reference to a local variable, not the array itself. This can simplify your code significantly:

res => {
    for(let i = 0, l = this.commissioners.length; i < l; i++) {
        if (this.commissioners[i]._id === res._id) {
            this.commissioners[i] = res;
            break;
        }
    }
}

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

Tips for showing the upcoming week in an angular application

Could someone please assist me with displaying the dates for the next 7 days using TypeScript? I am familiar with obtaining the date for the 7th day ahead, but I am unsure on how to generate a list of the 7 consecutive days. ...

`What specific type should be assigned to the custom styled input component in MUI?`

Hey team! Would you mind helping me out with this issue? The Mui documentation suggests setting a type for a Mui Styled component like this: const MyComponent = styled(MuiComponent)(({ theme }) => ({ // styling })) as typeof MuiComponent This method ...

Troubleshooting: Angular CLI project encountering issues on Internet Explorer

Today, I encountered an issue when attempting to create a new project using the Angular CLI. An exception is thrown on IE11 and the console displays the following error message: SCRIPT5007: Unable to get property 'call' of undefined or null ref ...

Assigning value to a member variable in a TypeScript Angular class

Currently, I am in the process of learning Angular. To enhance my skills, I am developing a simple web application using Angular and Spring Boot. One challenge I encountered is assigning a variable to the member variable of a Class. import { Injectable } f ...

Angular version 4 JSONP request callback

Currently, I am working on the migration of an Angular 1 application to Angular 4. One particular challenge I have encountered is a jsonp call to an endpoint over which I have no control. In the Angular 1 app, the following code snippet is being used: js ...

Basic library using babel, TypeScript, and webpack - Error: (...) is not a recognized function; within Object.<anonymous>

Recently, I encountered a strange issue while trying to bundle a simple function using babel, typescript, and webpack. You can find the example that is not working at this link. To test it, simply download the code, run npm/yarn install, npm/yarn run buil ...

The data type 'string[]' cannot be assigned to the data type 'listData[]'

I'm currently developing a flexible component that allows the list view to be utilized by different components. However, the challenge arises from the fact that each component has a different data format. In my project, I'm unable to use type any ...

Unlock the canGoBack feature in your Ionic 5 app with these simple steps!

I'm currently working on implementing a back button in my Ionic app, but I am running into an issue. I need to hide the back button when it's at the root level, which is dynamic and can change based on the flow of the app. I came across some code ...

A guide on setting up dual observables in Angular 2

Currently, I am implementing Observable in angular 2 with rxjs. As part of my demonstration, I have utilized fromEvent in a Plunker. Here is the link to my demo: https://plnkr.co/edit/zkgEcdn21CvIKoOycUOy?p=preview In this demo, I have included two input ...

Perpetually launching "npm start" on the server

I have been attempting to deploy an angular2 test application on a server. It is functioning well on my local machine using the command NPM start as indicated in my package.json file: "start": "concurrent \"npm run tsc:w\" \"npm run lite&bs ...

The Cypress tests run successfully on a local machine, but encounter issues when running on Gitlab CI

My current setup involves utilizing Cypress to test my Angular application. Interestingly, everything runs smoothly when I execute the tests locally. However, the scenario changes once I run the tests in Gitlab CI as it ends up failing. Looking at my pack ...

What steps do I need to take to mark an Angular form field as invalid using manual input?

I need help with a login form validation issue. When a user enters invalid credentials, I want to mark both the email and password fields as invalid and display a message indicating that the login failed. Can anyone guide me on how to achieve this using an ...

'The object of type '{}' does not support indexing with a 'string'

I am currently working on a React component that dynamically generates an HTML Table based on an array of objects. The columns to be displayed are specified through the property called tableColumns. While iterating through the items and trying to display ...

The directive for accepting only numbers is not functioning in versions of Chrome 49.xx.xx and earlier

I have implemented a directive in Angular 6 to allow only numbers as input for certain fields. The directive code is shown below: import { Directive, ElementRef, HostListener } from '@angular/core'; @Directive({ selector: '[NumbersOnly]& ...

A TypeScript/Cypress command that restricts input parameters to specific, predefined values

I have a Cypress command with a parameter that I want to restrict so it only accepts certain values. For example, I want the columnValue to be limited to 'xxx', 'yyy', or 'zzz'. How can I achieve this? Cypress.Commands.add( ...

Why is it necessary to use "new" with a Mongoose model in TypeScript?

I'm a bit confused here, but let me try to explain. When creating a new mongoose.model, I do it like this: let MyModel = moongoose.model<IMyModel>("myModel", MyModelSchema); What exactly is the difference between MyModel and let newModel = ne ...

Exploring TypeScript Heartbeat functionality with Nodejs ws module

I am currently in the process of setting up a WebSocket server using NodeJs and TypeScript. The WebSocket server implementation I have chosen is from the ws package, supplemented by the @types/ws package for typings. My goal is to have the server send out ...

Ngrx: When using CatchError, it does not trigger a dispatch of an action

Dealing with catchError in the latest version of ngrx. effect$ = createEffect(() => this.actions$.pipe( ofType(contactAction), switchMap(({ data }) => this.postService.contact(data).pipe( map(() =& ...

Error occurs when a value is passed to a component after it has already been checked for changes

Whenever I try to pass a value as input to a custom child component, I keep encountering the error message indicating that the expression has changed after being checked. The structure of the child component is as follows: <mat-card *ngIf="user$ | asyn ...

Angular8 Chart.js customizes the Y axis tick labels

Is there a way to dynamically adjust the Y-axis ticks in a chart.js graph? I attempted to modify them using the following commands: this.chartOptions.scales.yAxes[0].ticks.min = 10; this.chartOptions.scales.yAxes[0].ticks.max = 18; ...