Angular在对象数组中添加新对象后不会更新
创始人
2024-10-30 19:30:53
0

这可能是由于Angular对数组中的对象进行了浅层比较而导致的。为了解决这个问题,您可以使用切换数组引用的方法来更新视图。可以通过以下两种方式之一实现:

方法一:

在您的组件中,创建一个新的数组,然后使用 Array.push() 方法将新对象推入该数组。然后将该数组分配给原始数组的引用。这将强制Angular重新渲染组件,并更新视图,使新对象显示出来。

示例代码如下:

originalArray: Object[] = [{id: 1, name: 'John'}, {id: 2, name: 'Doe'}]; newObject: Object = {id: 3, name: 'Alice'};

addToOriginalArray() { let tempArray = this.originalArray.slice(); // create a copy of original array tempArray.push(this.newObject); // push new object to temp array this.originalArray = tempArray; // assign temp array to original array reference }

方法二:

使用 Angular 的 change detection 将变更检测策略更改为 OnPush。这将防止Angular每次更改检查时都进行全面调用,并使它仅在输入对象更改时才调用。在这种情况下,您需要通过具有新值的对象将输入对象重写。

示例代码如下:

import {Component, Input, ChangeDetectionStrategy} from '@angular/core';

@Component({ selector: 'app-my-component', templateUrl: './my-component.component.html', styleUrls: ['./my-component.component.css'], changeDetection: ChangeDetectionStrategy.OnPush // change change detection strategy }) export class MyComponent { @Input() originalArray: Object[] = [{id: 1, name: 'John'}, {id: 2, name: 'Doe'}]; @Input() newObject: Object = {id: 3, name: 'Alice'};

addToOriginalArray() { let tempArray = this.originalArray.slice(); // create a copy of original array

相关内容

热门资讯

透视科技!aapoker公共底... 透视科技!aapoker公共底牌(透视)透视软件(原来真的是有挂);1、透视科技!aapoker公共...
透视肯定!aapoker怎么控... 透视肯定!aapoker怎么控制牌(透视)插件(其实真的是有挂)1、金币登录送、破产送、升级送、活动...
透视游戏!aapoker透视怎... 透视游戏!aapoker透视怎么用(透视)免费透视脚本(一直是有挂);aapoker透视怎么用软件透...
透视透视!aapoker透视脚... 透视透视!aapoker透视脚本下载(透视)透视软件(总是有挂)运aapoker透视脚本下载辅助工具...
透视有挂!aapoker怎么设... 透视有挂!aapoker怎么设置抽水(透视)辅助插件工具(好像真的是有挂)1、在aapoker怎么设...
透视计算!aapoker辅助插... 透视计算!aapoker辅助插件工具(透视)脚本(好像真的有挂)1、超多福利:超高返利,海量正版游戏...
透视总结!aapoker透视脚... 透视总结!aapoker透视脚本入口(透视)ai插件(本来真的是有挂);1、aapoker透视脚本入...
透视辅助!aapoker透视方... 透视辅助!aapoker透视方法(透视)透视方法(真是存在有挂)1、很好的工具软件,可以解锁游戏的a...
透视好友房!aapoker透视... 透视好友房!aapoker透视脚本入口(透视)发牌逻辑(一直有挂)1、不需要AI权限,帮助你快速的进...
透视了解!aapoker怎么提... 透视了解!aapoker怎么提高中牌率(透视)透视脚本下载(其实真的是有挂)1、下载好aapoker...