0

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

3

1 Answer 1

2

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).

1
  • 1
    this.arr = [...this.arr] //<---- is not requiredCommentedNov 26, 2022 at 19:07

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.