aslary
aslary

Reputation: 403

Angular - Interpolation does not show current list items

I have a very small application in which there are two buttons. One button adds 1 to a list, the other one adds -1. Also, I am displaying the sum of the list.

Now I have one problem. I have a interpolation of the list and the newly added values are not displayed at all, but instead only the default ones which are initialized (see controller).

Here is my template:

<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 corresponding controller class 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);
  }
}

How can I display all items of the list with the interpolation syntax?

Upvotes: 1

Views: 237

Answers (1)

Ghoul Ahmed
Ghoul Ahmed

Reputation: 4806

Use immutable syntax like this

this.list = [...this.list, item];
  • You can always create a new reference to the array to allow trigger the OnChanges mechanism (change detection) See more
  • OnChanges Lifecycle Hook will trigger only when input property's instance changes, so you must have a new reference to activate change detection.

Working demo

Upvotes: 2

Related Questions