Angular - Binding not displaying the latest list elements

In my small application, I have two buttons that either add 1 or -1 to a list. The sum of the list is also displayed.

However, I am facing an issue with the interpolation as only the default values of the list are being displayed instead of the newly added ones.

Below is the template code:

<p>Items: {{ list }}</p> <!--This is not updating-->
<p>Sum: {{ getSumOfList() }}</p>
<button (click)="addItem(1)">Add 1</button>
<button (click)="addItem(-1)">Add -1</button>

The relevant controller looks like this:

export class HomeComponent implements OnInit {
  list: number[] = [1, 2, 3, 4, 5];

  constructor() { }

  ngOnInit(): void {
  }

  getSumOfList() {
    var total = 0;
    for (var i in this.list) { total += this.list[i]; }
    return total;
  }

  addItem(item: number) {
    this.list.push(item);
    console.log(this.list);
  }
}

I need help on how to display all items of the list using interpolation syntax.

Answer №1

Implement immutable syntax by utilizing the following:

this.list = [...this.list, item];
  • To enable the OnChanges mechanism (change detection), always create a fresh reference to the array Learn more
  • The OnChanges Lifecycle Hook will be activated only when there is a change in the input property's instance, necessitating a new reference for change detection.

View a demonstration here

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

How can I resolve a promise that is still pending within the "then" block?

Here is a piece of code that I have written: fetch(`${URL}${PATH}`) .then(res => { const d = res.json(); console.log("The data is: ", d); return d; }) When the code runs, it outputs The data is: Promise { <pending> ...

Generating form groups programmaticallyORDynamically

I recently utilized angular-archwizard to implement a wizard step with *ngFor However, I encountered an issue on how to create a dynamic formGroup for each step. In the code below, I managed to create a single formGroup for all steps, but my goal is to ha ...

What is the method to access an interface or type alias that has not been explicitly exported in TypeScript type definitions?

I am looking to create a new class that inherits from Vinyl. The constructor in the superclass takes a single parameter of type ConstructorOptions. export default class MarkupVinylFile extends Vinyl { public constructor(options: ConstructorOptions) { ...

What is the best way to assign a TypeScript type as the object type within an array of objects sourced from a different interface?

I am working with a generated interface that looks like this: export interface StaticPageLeftMenuV1 { id: string status: 'draft' | 'published' environments: ('dev' | 'staging' | 'production')[] ...

Boolean value 'isEdit' in Angular not being updated within the subscribe callback

Having a problem updating the isEdit component property within the event emitter's subscribe callback in my Angular application. Situation: In my CreateComponent, I handle adding or editing mobiles. The isEdit property (boolean) determines whether t ...

DateAdapter not found within Angular/Material/Datepicker - Provider not available

I need assistance with: angular / material / datepicker. My test project is running smoothly and consists of the following files: /src/app/app.module.ts import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from ' ...

What are the steps for manually integrating Bootstrap into an Angular project?

I'm currently working on an Angular 5 project within a private domain where I am unable to utilize the npm-install command. As a result, I have manually added Bootstrap's CSS and JS files to my project. I am now unsure how to properly link these ...

Is there a way to determine the distance in miles and feet between various sets of latitude and longitude coordinates?

I am working with an array of latitude and longitude coordinates and I am looking to use JavaScript or Typescript to calculate the distance in miles and feet between these points. const latsLngs = [ { lat: 40.78340415946297, lng: -73.971427388 ...

The @Input default value is being replaced by `undefined` within the testing environment

Within my component, I have the following input: @Input() someThing: string = 'm'; // default value When testing, I defined it as follows: @Component({ selector: 'app-test-wrapper-component', template: ` <app-my-component so ...

Uploading an Image to a SharePoint Group Folder using an Angular Application

I have a project in which I am developing an app using Angular to upload images to a SharePoint site. Specifically, I want to upload images from the Angular app to a private folder within a SharePoint group. I am utilizing Microsoft Graph API and Azure AD ...

Issue with Angular application failing to fetch data from JSON server

I've been attempting to retrieve data from a local server, but so far I'm not getting any results. The concept is to have a service handle the retrieval process and return an observable for any components in need of the data to subscribe to. dis ...

Navigating from a Card to a new View in Angular

I am currently developing a project using Angular (latest version). Within my application, I have the functionality to dynamically generate bootstrap cards from an Order Array and display them in my "Order-Item-Component through its respective template. ...

Navigating Through Angular Components

I have a layout with 3 components arranged like this: <app-header></app-header> <app-body></app-body> <app-footer></app-footer> However, I want to change the positioning of the footer and body as shown below: <app-he ...

The formatting in vscode does not apply to .tsx files

For a while now, I've relied on the Prettier extension in Visual Studio Code for formatting my code. However, since switching to writing React with Typescript, I now need to configure Prettier to format .tsx files accordingly. ...

Iterating through an array with ngFor to display each item based on its index

I'm working with an ngFor loop that iterates through a list of objects known as configs and displays data for each object. In addition to the configs list, I have an array in my TypeScript file that I want to include in the display. This array always ...

Automating the linking of tsd definitions with bower and npm: A step-by-step guide

Currently, I am in the process of transitioning an existing project to TypeScript which includes numerous bower and npm dependencies (bower.json and package.json). As mentioned on the tsd github page, TSD facilitates the discovery and linking of defini ...

Is there Polyfill Compatibility for Custom Elements in Angular 9?

When it comes to polyfilling support for custom elements created with Angular, there are various recommendations available. This demo demonstrates that adding the following polyfill in polyfills.ts works: import '@webcomponents/webcomponentsjs/custo ...

Development of backend applications using Node.js and Express, coupled with frontend interfaces built with Angular

I created a web application, utilizing Node.js with Express and MySQL for the backend, and Angular framework for the frontend. Check here While everything works smoothly in my local environment (using Mamp and port 3000 for testing), I am encountering dif ...

What is the proper way to include type annotation in a destructured object literal when using the rest operator?

When working with objects, I utilize the spread/rest operator to destructure an object literal. Is there a way to add type annotation specifically to the rest part? I attempted to accomplish this task, but encountered an error when running tsc. const { ...

Ways to resolve NPM dependency conflicts

Attempting to set up all the necessary npm packages for the AWS sample demo found at https://github.com/aws-samples/amazon-chime-sdk-classroom-demo on my laptop has been a bit challenging. Every time I try to run npm install I can't help but wonder i ...