Angular - Automatically update array list once a new object is added

Currently, I'm exploring ways to automatically update the ngFor list when a new object is added to the array. Here's what I have so far:

component.html

    export class HomePage implements OnInit { 
  collections: Collection[];
  public show = true;
  constructor(){}

  ngOnInit(){
    this.collections = this.collectionList;
  }

  _collections: Collection[] = [
      new Collection('i1', 'Range Rover', 'Model 2019'),
      new Collection('i2', 'Lancer Evolution', 'Model 2008')
    ]

  get collectionList() {
      return [...this._collections];
  }

  addItem(){
    this.testAdd();
  }

  testAdd(){
      this._collections.push(new Collection('i3', 'Chevrolet Camaro', 'Model 2020'));
  }

component.ts

<ion-content>
  <ion-col *ngFor="let col of collections;">
    <div>{{col.title}}</div>
    <div>{{col.description}}</div>
  </ion-col>
  <div style="padding-top:10px;">
        <button type="submit" class="label-center" (click)="addItem()">Add new item</button>
  </div>
</ion-content>

Check out the stackblitz link for more details.

Any insights on what could be missing in my approach?

Answer №1

Only at the initialization of ngOnInit, is the collections variable assigned the value of the _collections variable.

If a new value is added to the _collections array, it does not affect the collections array because it is a separate copy of the original array and not a referenced version of _collections.

To achieve the desired outcome, make the following adjustment:

testAdd(){
      this.collections.push(new Collection('i3', 'Chevrolet Camaro', 'Model 2020'));
  }

Another approach :

By using the spread operator, a new array is returned. To establish a reference between the _collections array and the collectins array, modify the get function as follows:

 get collectionList() {
      return this._collections;
  }

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

An error occurred when attempting to use the getDoc() function from Firebase within Next.js: TypeError - reading 'map' on properties of undefined

Hello everyone at StackOverflow, I ran into a problem while attempting to use .map() on a getDoc() constant in my Next.js application. The error message I'm getting is: "TypeError: Cannot read properties of undefined (reading 'map')". As a n ...

I'm having trouble with res.redirect, why isn't it redirecting me as expected?

In my login controller, I have a form that updates the user's scope when they click a button triggering the login() function. .controller('loginCtrl', ['$scope','$http',function($scope,$http) { $scope.user = { ...

Receiving user input in ajax

I have an operational PHP page with an AJAX call. I am currently attempting to obtain user input through a text entry field and then pass it through _GET into AJAX. Here is the code snippet: <body onload="test()"> <script> function test () { v ...

Choosing onSelect is quicker than opting for click

Utilizing the autosuggestion plugin with the onSelect option that changes values in other fields is causing an issue. Everything works fine initially when selecting an item, but when clicking on the input field with the .auto class for the second time (whe ...

Guidelines for combining inner objects with their parent in Javascript

I need assistance with using the filter function in Angular.js because it's not working on objects. Is there a way to merge a nested object into its parent using Javascript? For example, I have the following data structure: { "data" : [ { "ch ...

"How to eliminate the hash symbol from a URL using react-router-dom in a React.js

Recently started learning react.js and running into an issue with the URL structure while using react-router-dom v6 in my project. Specifically, I'm finding a problem with the # symbol in the URL. For instance: {url}/#/dashboard I would like it to b ...

Angular 2/4 throws an Error when a Promise is rejected

I implemented an asynchronous validator function as shown below. static shouldBeUnique(control: AbstractControl): Promise<ValidationErrors | null> { return new Promise((resolve, reject) => { setTimeout(() => { if (contr ...

Text that appears as an HTML button is displayed after being compiled using the $

I am attempting to generate a pop up dialog with two buttons using JS code in angular. The script below is what I am using to create the buttons... var html = $('<button ng-click = "cancelAlert()" > Cancel</button > <button ng-click="c ...

Find the highest array within a multidimensional array by sorting it based on the value of a specific column

In my code, there is an array named $aSumGame containing the following data: Array ( [682] => Array ( [nature] => 682 [totalGames] => 3 [category] => super ) [707] => Array ( [nature] => 707 ...

ngOnChange event not firing despite attempting various solutions

My goal is to utilize ngOnChanges to update a string (even or odd) after another variable (counter) changes. However, I am encountering an issue where the value of the message remains blank and does not update when the counter changes. export class Counter ...

Troubleshooting problem with updating a record in the MongoDB using Node.js and

Currently, I am developing a REST API using Node, Express, and MongoDB. I have successfully implemented fetch, create, and delete functions but facing issues with the update function. Every time I attempt to test it using Postman, the code hangs, the serve ...

Angular 5 introduces a bespoke directive that allows for element repetition within the framework

Looking to create a directive that contains an array of elements, and when the directive is bound to any element, that element will repeat the number of times equal to the length of the array. For example, if the array has 3 elements, the element will re ...

Having trouble with your contact form and not getting it to work properly with Javascript, Ajax, or

I've been struggling to get a contact form working for an entire day. I included the following script at the top of my page: <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script> This is the structure ...

employing the d3.queue method to defer execution until receiving the AJAX response

Seeking examples of integrating AJAX, d3, and PHP to extract data from a database and create graphs. Any guidance would be appreciated. I am currently using d3 to generate a force chart based on database information retrieved through AJAX and PHP. I have ...

What is the best way to retrieve JSON data from a variable once it has finished loading?

let jsonDataNewsFeedGlobal; jsonDataNewsFeedGlobal = $.getJSON('').done(function(data) { console.log(data); console.log(data.source); }); My Challenge: I see my mistake now, I should have been using "data" instead of "jsonDataNewsFeedGlobal ...

Navigating with Vue.js using programmatic methods while passing props

I am working with a Vue component that includes a prop called 'title' like this: <script> export default { props: ['title'], data() { return { } } } </script> After completing a specific action, I need to pro ...

"Ensuring the right data type is selected for the onChange event

In my code, I have a simple select component set up like this. import { Controller } from "react-hook-form"; import Select, { StylesConfig } from "react-select"; //.. const [universe, setUniverse] = useState<SetStateAction<TOptio ...

Using a targeted div as a child component in React

How can I specifically pass a div with the class name 'message-content' as props.children, without including all the divs above it? <div className="message"> <div className="message-title-info">A ...

Utilizing the power of KendoUI and Angular2 for autocomplete: governing accepted values

I successfully integrated the KendoUI Autocomplete feature with live search functionality. It is working well and meeting my expectations. However, I want to limit the autocomplete suggestions to values from the list only. For example, if I type "London" ...

Randomly choose one of 5 pages and insert an HTML element at different intervals using JavaScript, jQuery, MySQL, or PHP

Suppose we have the following HTML element: <img src="icon.png"> Our website consists of 5 pages: index.php products.php register.php about.php terms.php How can we randomly place this HTML element on one of the pages, ensuring it stays there for ...