简体   繁体   English

如何防止* ngFor更新Angular 4中的DOM?

[英]How to prevent *ngFor from updating the DOM in Angular 4?

In angular 4, I'm using *ngFor to show some images 在角度4中,我使用* ngFor显示一些图像

<div  *ngFor='let image of images;let i = index'>
    <img  [src]="'/assets/Images/'+image+'.png'" *ngIf="!tohide(i,0);">
</div>

After *ngFor is done for the first time, I wish to remove a specific image via *ngIf, without changing the array 'images'. 第一次完成* ngFor之后,我希望通过* ngIf删除特定图像,而不更改数组'images'。 The problem is whenever I removed an image with my function 'tohide', *ngFor bind again to the 'images' and update the set of images. 问题是每当我使用函数“ tohide”删除图像时,* ngFor再次绑定到“ images”并更新图像集。

In other words, is there a way to force *ngFor to not to listen to the array 'images' occasionally? 换句话说,有没有办法强迫* ngFor偶尔不听数组“图像”?

*ngFor has a track by function by default, in your case, you want to override it. *ngFor默认情况下具有按功能跟踪的轨道,在这种情况下,您要覆盖它。

<div  *ngFor='let image of images;let i = index; trackBy: myTrackByFunction'>
  <img  [src]="'/assets/Images/'+image+'.png'" *ngIf="!tohide(i,0);">
</div>

In your TS 在您的TS中

myTrackByFunction(index, item) {
  return index; // or item.id, if your image has an ID
}

For more information, see this web page 有关更多信息, 请参见此网页

u can specify another property i your array named "removed": False and then use this: 您可以在您的名为“ removed”的数组中指定另一个属性:False,然后使用此属性:

<div  *ngFor='let image of images;let i = index'>
<img  [src]="'/assets/Images/'+image+'.png'" [hidden]="i.removed">

whenever u want to remove an item without really remove it from array just set "removed" property to True. 每当您要删除项目而不真正将其从数组中删除时,只需将“ removed”属性设置为True。

You can use following as one of the appropriate ways to solve this: 您可以使用以下方法作为解决此问题的适当方法之一:

  1. You can track remove status of each image object by adding a property called removed set to false initially. 您可以通过添加一个名为财产跟踪每个图像对象的删除状态removed设置为false开始。
  2. You then implement a filter (as explained here ) with *ngFor to filter out the images. 然后,您实现一个过滤器(如解释在这里 )与*ngFor过滤掉图像。
  3. When you remove an image, set the removed flag to true. 当您删除图像时,将已removed标志设置为true。 This will filter out the removed image. 这将滤除删除的图像。

Edit: the trackBy is another parameter for *ngFor which you can use instead of developing a separate filter. 编辑: trackBy是* ng的另一个参数,您可以使用它代替开发单独的过滤器。 The filter would give you additional control and features if you need so. 如果需要,过滤器将为您提供其他控制和功能。

Hope this helps! 希望这可以帮助!

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

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