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

相关内容

热门资讯

2分钟细说!佛手在线是不是有挂... 2分钟细说!佛手在线是不是有挂,wepoker透视脚本安卓,安装教程(有挂方法);1.佛手在线是不是...
查到实测!wepoker手机助... 查到实测!wepoker手机助手,拱趴大菠萝挂哪里,解说技巧(有挂技巧)准备好在拱趴大菠萝挂哪里ia...
必备教程!德普之星透视辅助,哈... 必备教程!德普之星透视辅助,哈糖大菠萝怎么挂,曝光教程(有挂软件);实战中需综合运用上述技巧,并根据...
玩家必看攻略!红龙poker辅... 玩家必看攻略!红龙poker辅助工具,pokernow辅助工具,详细教程(有挂辅助)是一款可以让一直...
推荐一款!poker worl... 推荐一款!poker world辅助,hhpkoer辅助挂是真的吗,透明挂教程(有挂神器)这是由厦门...
我来教教大家!newpoker... 我来教教大家!newpoker脚本,wepoker辅助插件功能,解说技巧(有挂神器);建议优先通过w...
信息共享!wejoker透视方... 信息共享!wejoker透视方法,hhpoker辅助挂下载,科技教程(有挂攻略);致您一封信;亲爱h...
玩家攻略!hhpoker透视脚... 玩家攻略!hhpoker透视脚本视频,hhpoker辅助软件,必备教程(有挂攻略);1分钟了解详细教...
推荐一款!aapoker如何设... 此外,数据分析德州(aapoker如何设置胜率)辅助神器app还具备辅助透视行为开挂功能,通过对客户...
如何分辨真伪!约局吧德州真的有... 如何分辨真伪!约局吧德州真的有透视挂吗,aapoker怎么拿好牌,2025新版(有挂方法)1、许多玩...