简体   繁体   English

Angular 6 - 更改变量但不刷新视图

[英]Angular 6 - changing the variable but doesn't refresh the view

I have an array variable, which contains objects, just like this: 我有一个数组变量,它包含对象,就像这样:

[{name: 'Name 1', price: '10$'}, {name: 'Name 2', price: '20$'}, ...]

I have a view, which prints out the list of the products, like this: 我有一个视图,打印出产品列表,如下所示:

<div *ngFor="let item of items">
   {{item.name}} - {{item.price}}
</div>

This is just an example but the 'model' of the problem is the same: 这只是一个例子,但问题的“模型”是相同的:

If I change the 'items' array from the code (for example because an external event occured) the variable value is changes, but the view won't refreshed :(. 如果我从代码中更改'items'数组(例如因为发生了外部事件),则变量值会更改,但视图不会刷新:(。

How can I make this work? 我怎样才能做到这一点?

Edit: 编辑:

changeArray() includes only one line: changeArray()只包含一行:

changeArray(items) : void{ this.items = items; }

Maybe the problem is that, I call this method of A, from an another component? 也许问题是,我从另一个组件中调用A的这种方法? So, in component 'B', I have a line just like this: 所以,在组件'B'中,我有一条如下:

a.changeArray(items);

Angular expects arrays to be immutable. Angular期望数组是不可变的。 You cannot alter the contents of the array, but need to create a new one (change the reference). 您不能更改数组的内容,但需要创建一个新的(更改引用)。

As an example use concat which returns a new array instead of push to add elements. 作为示例,使用concat返回一个新数组而不是push来添加元素。

One way to force refresh the list is to use the spread operator ... 强制刷新列表的一种方法是使用扩展运算符...

So after you have updated your (say) items property in your component, do this, 因此,在更新组件中的(say) items属性后,执行此操作,

// after items are updated logic, and assuming it is an array,
this.items = [...this.items];

this should refresh your list. 这应该刷新你的清单。

If you provide your entire code to replicate the problem, this force change approach may be fine tuned. 如果您提供整个代码来复制问题,则可以对此强制更改方法进行微调。

UPDATE: 更新:

Based on your comments, 根据您的意见,

update the changeArray() to this, changeArray()更新为此,

changeArray(items) : void{
  this.items = [...items];
}

UPDATE2: UPDATE2:

If the above doesn't work, try this too, 如果上述方法无效,请尝试以下方法,

in the component where changeArray() is defined, add this to the constructor and import ChangeDetectorRef as well, 在定义了changeArray()的组件中,将其添加到constructor并导入ChangeDetectorRef

import { ChangeDetectorRef } from '@angular/core';

constructor(cRef: ChangeDetectorRef) {}

changeArray(items) : void{
  this.items = [...items];
  this.cRef.detectChanges();
}

Hope it works. 希望它有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM