Angular fails to refresh object array when new object is added

Currently, I am immersed in a project that involves using angular-google-map (agm) and incorporating various polygons to represent different elements. However, I have encountered an issue where my object array fails to update when I attempt to draw on the map in order to obtain a collection of coordinates for implementation.

In brief, my problem lies in the fact that my object array does not reflect updates when I utilize the .push method.

In the home.component.ts file:

export class HomeComponent implements OnInit {

ngOnInit(): void { 
}

constructor(private cr: ChangeDetectorRef) { }

// Here is my initial polygon values
pathsLs: any[] = [[
  { lat: 43.51270075713179, lng: 16.468134790981548 },
  { lat: 43.51205153579524, lng: 16.46757689150645 },
  { lat: 43.5119745090715, lng: 16.466895610416667 },
  { lat: 43.51273927004248, lng: 16.466659576023357 },
  { lat: 43.51284380496191, lng: 16.467753917301433 },
  
]]
pointList: { lat: number; lng: number }[] = [];

// This function is used to update the Object array

addSomething() {
  this.pathsLs.push(this.pointList);
  this.pathsLs = [...this.pathsLs];
  this.cr.detectChanges();
}


The issue arises when I invoke this function; although I can observe the updated data in console.log(this.pathsLs) and see the polygon drawn on the map correctly, upon refreshing the page, everything reverts back to the initial values. Hence, I am wondering if there is a means to physically display this change, for instance:

If I were to execute something like this

this.pathsLs.push([{ lat: 43.51174, lng: 16.46538 }])
to reflect the following in my typescript file:

pathsLs: any[] = [[
    { lat: 43.51270075713179, lng: 16.468134790981548 },
    { lat: 43.51205153579524, lng: 16.46757689150645 },
    { lat: 43.5119745090715, lng: 16.466895610416667 },
    { lat: 43.51273927004248, lng: 16.466659576023357 },
    { lat: 43.51284380496191, lng: 16.467753917301433 },
    
  ],[{ lat: 43.51174, lng: 16.46538 }] <-- newly added
]

Answer №1

Check out the Stackblitz example

After reviewing the comments, it is clear that for persistent data changes, it's recommended to retrieve data from a persistent source such as local storage or a server.

To achieve a separation of concerns, consider using a service to manage storage, a container to facilitate communication, and a reusable child component to display the data.

In a parent container component, fetch the paths and pass them down to the child component for display:

<app-child-component [pathLs]="pathLs"></app-child-component>

The child component receives the paths using @Input() and renders them accordingly:

@Input() pathLs: IPathL[][] = [];

Additionally, here is an example of a local storage service implementation:

import { Injectable } from '@angular/core';
import { IPathL } from './paths.model';

@Injectable()
export class PathsLocalStorageService {
  // Implementation details go here...
}

Consider transitioning the service API to utilize Observables and server interactions. A common approach is to start by mocking the service with local storage, updating component usage, and eventually integrating server communication.

import { of } from 'rxjs'
...
@Injectable()
export class PathsLocalStorageService {
  // Updated methods using Observables...
}

Answer №2

Have you tried using the HTML component to invoke the addSomething() function?

It seems like your component is not calling the function.

Additionally, take a look at your 'pointList' array - you are currently pushing an empty array into it.


Regarding your log, you may need to push to array[0] since you are working with an array of arrays.

pathsLs: any[] = [[
    { lat: 43.51270075713179, lng: 16.468134790981548 },
    { lat: 43.51205153579524, lng: 16.46757689150645 },
    { lat: 43.5119745090715, lng: 16.466895610416667 },
    { lat: 43.51273927004248, lng: 16.466659576023357 },
    { lat: 43.51284380496191, lng: 16.467753917301433 },
    
  ],[{ lat: 43.51174, lng: 16.46538 }] <-- newly added
]

With pathsLs: any[] = [[]], you are currently pushing data into the parent array when you should be pushing into the child array;

It appears to be an issue with how you have declared it.

pathsLs: any[] = [
    { lat: 43.51270075713179, lng: 16.468134790981548 },
    { lat: 43.51205153579524, lng: 16.46757689150645 },
    { lat: 43.5119745090715, lng: 16.466895610416667 },
    { lat: 43.51273927004248, lng: 16.466659576023357 },
    { lat: 43.51284380496191, lng: 16.467753917301433 }
]

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 passing e: EventTarget as a forwarded prop through a wrapper component, Typescript raises an error about the missing "value" property in the onChange function

In my project, there is a custom component called SelectField that serves as a wrapper for rendering label, helper text, and select input (inspired by TextField from @material-UI). The SelectField component exposes props like value and onChange, which are ...

Navigating through errors in my Dockerfile while running Angular

As a complete novice in the world of Docker (although quite comfortable with the rest of my tech stack), I followed along with the Docker guide and ended up with this Dockerfile: FROM angular/ngcontainer:latest WORKDIR /ClientApp COPY . . RUN npm install - ...

Having Trouble Adding Details to a New Cart for a User in Angular and MongoDB - What's Going On?

After working on an E-Commerce site for a while, I hit a roadblock. Despite taking a break and coming back with determination, I can't seem to resolve the issue at hand. The application features registration, login, product search, and a popup window ...

Implement new interface methods on-the-fly

I am seeking a way to dynamically incorporate methods that are defined in an interface. Initially, I considered using the index signature approach, but unfortunately, not all methods have the same signature. My objective is to preserve all type information ...

Generating a date without including the time

I recently started working with React (Typescript) and I am trying to display a date from the database without including the time. Here is my Interface: interface Games { g_Id: number; g_Title: string; g_Genre: string; g_Plattform: string; g_ReleaseDate: ...

Issue occurred while trying to render a React component with Typescript and WebPack

I am in the process of creating a basic React component that simply displays a page saying Hello. However, I'm encountering an error in my console. My compiler of choice is TypeScript. To set up my project, I am following this guide: https://github.co ...

Is it possible to deactivate input elements within a TypeScript file?

Is it possible to disable an HTML input element using a condition specified in a TS file? ...

Join a subscription and remain subscribed in sequential order

Within the code below, there is a nested subscribe function. It takes a schedule_id and retrieves questions based on that schedule_id. The functionality works correctly, but the order in which getQuestion() is executed is not guaranteed. Schedule IDs: 111, ...

Customize your Joi message using the .or() method

I'm attempting to personalize a message for the .or() function in Joi, similar to this: https://i.stack.imgur.com/68dKx.png The default message from Joi is as follows: Validation Error: "value" must contain at least one of [optionOne, optionTwo] ...

What are the steps to connecting incoming data to an Angular view utilizing a reactive form?

Hello, I am currently fetching data from an API and have successfully displayed the teacher values. However, I am unsure of how to utilize the incoming array values for "COURSES" in my Angular view. This is the response from the REST API: { "courses ...

In order to incorporate Bootstrap with Angular2, I had to execute a specific command

For incorporating bootstrap with angular2, I executed the following command: $ npm install --save @ng-bootstrap/ng-bootstrap The output displayed: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="40212e27352c2132726d313529232 ...

Ways to employ data binding for extracting a user-input value and performing multiplication operations with the enclosed {{ ...}} tags

My API response includes the price of a product, which is represented as {{price}} I have a system where I can add or reduce the number of products: <div class="number-input"> <h2>Price: {{price }}</h2> <button oncli ...

Transfer a reference from one list to another within the Redux store

Within my store, I have various lists that contain unique identifiers referencing normalized entities. The structure is typically as follows: { list1: [ 1 ], list2: [], //other lists entities: { 1:{data}, ... } } Users have the abil ...

What is the best way to eliminate the content of an element using javascript/typescript?

The progress bar I'm working with looks like this: <progress class="progress is-small" value="20" max="100">20%</progress> My goal is to use javascript to remove value="20", resulting in: <progre ...

Type returned by a React component

I am currently using a basic context provider export function CustomStepsProvider ({ children, ...props }: React.PropsWithChildren<CustomStepsProps>) => { return <Steps.Provider value={props}> {typeof children === 'function&ap ...

Directly within Angular, map the JSON data to an object for easy assignment

I came across this information on https://angular.io/guide/http. According to the source, in order to access properties defined in an interface, it is necessary to convert the plain object obtained from JSON into the required response type. To access pr ...

Exploring how to set dropdown menu width for Angular2 mat-select options

Currently, I am using the angular2 mat-select control and facing an issue with the width and position of its dropdown list menu. By default, it is wider and overflows the element on both sides by a few pixels. I have not found any option for adjusting the ...

Utilize the forEach method with a TypeScript wrapper class containing a list

After replacing a list with a wrapper class that allows for monitoring changes to the list, I noticed that I can no longer use the forEach statement to iterate over the class. let numberList = new EventList<number>([1,2,3,4]); numerList.forEach((elem ...

Initial value not being recognized by mat-input attribute disable

My current challenge involves toggling the enable/disable status of mat-inputs based on a specific property value within an object. Within my component, I am subscribing to an observable in my service that retrieves applications with a default disabled fl ...

Exploring the World of Angular: Abstracts and Data Transformations

Facing a perplexing issue with a component that is based on an abstract class, or at least that's my assumption. There are multiple sibling components rendered using *ngFor based on an array length. These siblings, derived from an abstract class, rec ...