I share array of objects to my components trough service. So in one moment I want to replace one of the array object's properties with the properties of new object(I replace the object). So my shared object should update in all templates where it is used.
https://plnkr.co/edit/0sRxSivEaEPLsNAJo7MV?p=preview
// my.component.ts
@Component({
selector: 'my-component',
template: '<div>MyComponent: {{item.name}}</div>',
})
export class MyComponent implements OnInit {
constructor(private myService: MyService) {}
private item = myService.myListData[0];
ngOnInit() {
// 1. - This triggers change detection in app.ts template
this.item.name = 'Name 1111';
setTimeout(() => {
// 2. - This doesn't trigger change detection in app.ts template
let newObj = {name: 'Name 222', age: 225};
this.item = newObj;
}, 3000);
}
}
In my case //1 change template value in app.ts and my.component.ts but //2 trigger change only in my.component.ts
I'm wondering why //2 is doesn't update app.ts template and is there a way to do it without looping trough object properties?
Update: I managed to solve my issue by using Object.assign(). There is no change detection when replacing objects.
setTimeout(() => {
// 2. - This doesn't trigger change detection in app.ts template
let newObj = {name: 'Name 222', age: 225};
Object.assign( this.item , newObj);
}, 3000);