EMahan K
EMahan K

Reputation: 467

How to update array object value in angular

Trying to update array object value but not working. I am trying to update item value from an array But not updating. How to resolve this issue.

  ngOnInit() {
this.arr = [
  {
    lable: 'test1',
    item: 'Row6',
  },
  {
    lable: 'test2',
    item: 'Row9',
  },
  {
    lable: 'test3',
    item: 'Row4',
  },
];
}

 updateVal() {
    this.arr = this.arr[0].item = 'Row9';
    console.log(this.arr);
 }

Demo: https://stackblitz.com/edit/angular-ivy-srsirm?file=src%2Fapp%2Farrcom%2Farrcom.component.ts

Upvotes: 0

Views: 289

Answers (1)

Cedric
Cedric

Reputation: 552

TL;DR This will probably work

 updateVal() {
   this.arr[0].item = 'Row9';
   this.arr = [...this.arr]
 }

I think you're confusing two concepts here.

  1. Yes, you're supposed to give Angular a new reference to the array/object to trigger the change detection (thus triggering a rerender)
  2. BUT, you're not supposed to assign the attribute to some string value (in your case 'Row9'.

If you're trying to change the value of exactly one element, you can change it inline with this.arr[0].item = 'Row9'. However, as you might observe, no new render will follow your action. The content of the object in the array will change. If you wan't to trigger a new render / the change detection, you need to create a new reference to the array, e.g., this.arr = [...this.arr] (basically moving all list elements into a new list).

Upvotes: 2

Related Questions