7

I have an property:

public rows: any[];

Then I fill this array in constructor:

this.rows.push({"id": 1, "subject": "Subject", "scope": "Learn basics", "hours": 2});

In template I iterate array like as:

<tr *ngFor="let p of rows; let i = index;">

So, if I remove element from array:

this.rows.splice(this.rows.length - 1, 1);

It does not change model, I see as before one row in array.

Jessie
  • 373
  • 2
  • 6
  • 17
  • `this.rows.splice(this.rows.length - 1, 1);` is probably called from code outside Angulars zone and change detection doesn't recognize the change. – Günter Zöchbauer Dec 07 '17 at 11:21
  • No, I call this in the same component class in method of class – Jessie Dec 07 '17 at 11:23
  • Could you try: `this.rows = this.rows.splice(this.rows.length - 1, 1);` and log splice afterwards. Oh and do you use AngularJs or Angular (just to verify) – Doomenik Dec 07 '17 at 11:25
  • Return a new array with the spread operator or using filter to get an element out. – AndreaM16 Dec 07 '17 at 11:26
  • `this.rows = this.rows.splice(this.rows.length - 1, 1);` returns always the same number of rows – Jessie Dec 07 '17 at 11:29
  • this.rows.splice(this.rows.length - 1, 1); shouldn´t it be just this.rows.splice(-1, 1); – Doomenik Dec 07 '17 at 11:34
  • in the constructor you set your `rows` array to have exactly one object. `this.rows.splice(this.rows.length - 1, 1)` goes to your `rows` array and returns a new array with exactly one item starting from position 0 in your original array. So actually, you are replacing your old array with the new one which has the same single object. Thus, nothing changes in HTML. (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice) – Andriy Dec 07 '17 at 11:36
  • No effect, the same result – Jessie Dec 07 '17 at 11:36
  • Do you mean to create new array/? – Jessie Dec 07 '17 at 11:38

4 Answers4

11

Angular doesn't recognise an array as having been changed if only it's contents have been changed. To let it know the array has changed just reassign the array object after removing an element and it should update on the DOM:

this.rows.splice(this.rows.length - 1, 1);
this.rows = [...this.rows];
Plog
  • 9,164
  • 5
  • 41
  • 66
1

re-assign the array so that angular can notice a change and update the array

1

In my case filtering array instead of splicing it worked out

array.splice(removeIndex, 1) // replaced with

array = array.filter(
  (element, index) => removeIndex !== index
)
paragonid
  • 241
  • 2
  • 8
0

Instead you could do the following

this.rows.splice(this.rows.indexOf(this.rows.length - 1), 1);