Ways to initiate update notification when altering an array object?

I am working on my Angular4 app and I have a component that uses a *ngFor directive to iterate over an array:

 <div *ngFor="let person of persons">
   {{person.name}}
   {{person.car}}
 </div>

Within the same component, there is a feature to delete a car. After successfully deleting a car using the deleteCar() method, I update the persons array as follows:

 deleteCar(car) {
   this.carService.deleteCar(car).subscribe(() =>  {
   this.persons.filter(obj => obj.car == car.name)
               .forEach(i => i.car = null);
   }
 }

The issue I'm facing is that the *ngFor loop does not get triggered when I make changes to an existing person object in the persons array. How can I fix this problem?

Answer №1

To efficiently handle this situation, I utilize array destructuring. While it may not be considered the optimal approach, it gets the job done.

this.items = [...this.items];

By altering the reference of the array in this manner, Angular is able to detect and acknowledge the changes made to the array.

Answer №2

To efficiently achieve this goal, it is recommended to utilize a behavior subject within a service and then access it within your component.

Here is an example of what your service class might look like:

@Injectable()
export class PersonService {

private persons = new BehaviorSubject<any[]>([]);
public persons$ = this.persons.asObservable(); // --> This can be accessed in your component

constructor() {
   // Set the initial values for the persons array here;
}

function deleteCar()//todo  

}

In your component:

constructor(private personService: PersonService) {

}

ngOnInit() {
    this.persons = this.personService.persons$; // Don't forget to use the async pipe or subscribe
}

delete(car){
    this.personService.deleteCar(car);
}

This method should effectively work.

For more information, refer to https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service

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

Limit the parameter of a TypeScript method decorator based on the method's type

Is it possible to generically restrict the argument of a method decorator based on the type of the method it is applied to? I attempted to obtain the method's type that the decorator is applied to using TypedPropertyDescriptor<Method>. However, ...

Next.js is experiencing issues with the build process

I encountered an issue while working on a Next.js project with NextAuth.js. The problem arises when I try to define my authOptions, as a TypeScript error indicates that the object is not compatible with the expected type for AuthOptions. Here's the sn ...

Encountering an issue with Angular 8 and Material where a table does not fully render on mobile browsers like Chrome, causing rows to only half

Currently, I have an Angular 8 application integrated with Material v8.2.3 where a table with expanding rows is being used. While everything functions perfectly on desktop browsers, there seems to be an issue when accessing the application on mobile phone ...

The issue with Angular Material Dialog hiding certain elements

In my Node.js Angular project, I am trying to implement a confirm dialog which should be a simple task. Utilizing Material styling to speed up development process. However, upon running the project, the opened dialog appears to be empty: https://i.sstati ...

BrowserRouter - The type '{ children: Element; }' is not compatible with the type 'IntrinsicAttributes', as they do not share any properties in common

After upgrading to React version 18, I encountered a type error with the BrowserRouter component. Despite trying various approaches, I am unable to pinpoint the root of the problem. Here is the error that pops up during debugging: Overload 1 of 2, &a ...

Ways to organize an Angular Material Design table during the rendering/creation process

After successfully implementing the sort feature for my angular material design table, I encountered an issue where the table does not automatically sort itself when the page loads. It only sorts when I manually click on the column header. I have tried usi ...

I encountered login issues when trying to access dist/index.html in my Angular 8 application, but I found a workaround by utilizing the proxy.conf.json file, which

I have been trying to login through the index.html page in the angular 8 dist folder, but I keep encountering an error with the login API URL. Despite spending two days on this issue, I have not been able to find a solution. If anyone has any suggestions o ...

Is it more appropriate to initialize my FormGroup in the container component or the presentational component? I appreciate your help

I'm working with Angular in my application, and I'm curious to know if the method I'm using is correct. My approach involves initializing a FormGroup in the container component and passing it as a prop to the presentational component. Thanks ...

"Upon studying the Reflect-metadata index.d.ts file, I find myself perplexed by the variances in

While utilizing the reflect-metadata package, I encountered this particular type. However, I am uncertain about its meaning and function signature. function metadata(metadataKey: any, metadataValue: any): { (target: Function): void; ( ...

Function in Typescript that accepts an array or a single instance of a constructor and then returns a list

UPDATE:: reproducible link to the TypeScript playground I have also found a solution in the provided link, but I am still open to learning why my initial approach didn't work. TLDR; This method does not yield the expected results getEntitiesByComp ...

Attempting to simulate the behavior of Angular2 Token during testing

Currently, I am working on obtaining a token that is required for API authentication to retrieve a list. My approach begins with importing the angular2-token library: import { Angular2TokenService } from 'angular2-token'; After this, I include ...

Is it possible to utilize useRef to transfer a reference of an element to a child component?

When I want to mount something into the element with id tgmlviewer, I call it a viewer object. This process works smoothly when there is only one component of this kind. import React, { useEffect } from "react"; import { Viewer } from "../.. ...

Executing a node.js function within an Angular 2 application

Currently, I am running an Angular2 application on http://localhost:4200/. Within this app, I am attempting to call a function located in a separate node.js application that is running on http://localhost:3000/. This is the function call from my Angular2 ...

"Utilize PrimeNG's p-tabpanel to bind a unique style class to

When using the tabview component from PrimeNG, I am encountering an issue where I am unable to bind a header style class. Here is my static HTML code that works: <p-tabPanel header="Title" headerStyleClass="badge" formGroupName=&quo ...

The function did not return a Promise or value as expected when using async and await

    I have been working on implementing this code structure for my cloud functions using httpRequest. It has worked seamlessly with those httpRequest functions in the past. However, I recently encountered an error when trying to use it with the OnWrite ...

How come TypeScript doesn't recognize my MongoDB ObjectID as a valid type?

Currently, I am working with Node.js, MongoDB, and TypeScript. The code snippet below is error-free: const ObjectID = require("mongodb").ObjectID; const id = new ObjectID("5b681f5b61020f2d8ad4768d"); However, upon modifying the second line as follows: ...

Errors in TypeScript Compiler for using react-bootstrap in SPFx project

After setting up an SPFX Project with Yeoman generator and including react-bootstrap as a dependency, I encountered errors when using react-bootstrap components and running gulp serve. The error messages are as follows; does anyone have any solutions to ...

Issues encountered while setting up @angular/google-maps on angular13

Every time I attempt to install, this error displays: npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="402d21306d212323 ...

Leveraging an external TypeScript library in a TypeScript internal module

Imagine you find yourself in a situation where you need to utilize a typescript/node library within an internal module that is spanned across multiple .ts files. ApiRepositoryHelper.ts import * as requestPromise from "request-promise"; module ApiHelp ...

TypeScript: The class results in an empty object being returned

I'm encountering an issue with a Typescript Class that I'm attempting to use. Even after instantiating it, I'm not getting the correct class instance. Class GamesService export interface IGame { name: string; online: number; likes: n ...