首页 > 解决方案 > Angular trackBy不更新dom

问题描述

大家好,这个我想不通。我正在向我的数组添加元素,但除非我刷新页面,否则我的 dom 不会更新。我在一个单独的组件中使用 trackBy 并且效果很好,但是在这个较新的组件上它根本不起作用。

这是我的html

<div class="accordion" id="accordionExample">
  <div class="card" *ngFor="let grocery of groceryList;trackBy:trackByIdCode; index as index;">
    <div class="card-header" [id]="'grocery1'+index">
      <h5 class="mb-0">
        <button class="btn btn-link" type="button" data-toggle="collapse" [attr.data-target]="'#grocery2'+index" aria-expanded="false" [aria-controls]="'grocery2'+index">
          {{grocery.recipeName}}
        </button>
      </h5>
    </div>

    <div [id]="'grocery2' + index" class="collapse" [aria-labelledby]="'grocery1'+index" data-parent="#accordionExample">
      <div class="card-body">
        <ul class="list-group" id="filterList">
          <li class="list-group-item">
            <a href="#" class="list-down-btn" data-toggle="#subgroup"><span class="glyphicon glyphicon-chevron-down"></span></a>
            <ul id="subgroup" class="list-group">
              <li class="list-group-item" *ngFor="let ingredient of grocery.ingredients">{{ingredient}}</li>
            </ul>
          </li>
        </ul>
      </div>
    </div>
  </div>
</div>

<mat-icon svgIcon="shopping_cart"></mat-icon>

这是我的组件代码:

import { Component, OnInit, NgModule,ChangeDetectorRef, ChangeDetectionStrategy } from '@angular/core';
import {GetRecipesService} from '../getrecipes.service';
import { MatIconRegistry } from "@angular/material/icon";
import { DomSanitizer } from "@angular/platform-browser";
@Component({
  selector: 'app-grocery-sidebar',
  templateUrl: './grocery-sidebar.component.html',
  styleUrls: ['./grocery-sidebar.component.css'],
  changeDetection: ChangeDetectionStrategy.Default,
  })
export class GrocerySidebarComponent implements OnInit {//

  constructor(getRecipesService: GetRecipesService,private matIconRegistry: MatIconRegistry,private domSanitizer: DomSanitizer,private cdr:ChangeDetectorRef) { 
    getRecipesService.getGroceryList().subscribe(promise=>{
      this.groceryList = promise.data;
  });
    this.recipeService=getRecipesService;
    this.matIconRegistry.addSvgIcon("shopping_cart",this.domSanitizer.bypassSecurityTrustResourceUrl("../assets/shopping-cart-solid.svg"));
  }

  addToGroceryList(recipeName,recipeIngredients){
    this.recipeService.addToGroceryList(recipeName,recipeIngredients).subscribe(promise=>{
      console.log("addToGroeryList Promise: "+promise);
      this.refreshGroceryList();
    });

  }

  refreshGroceryList(){
    this.recipeService.getGroceryList().subscribe(promise=>{
      console.log("refreshed groceryList: "+promise.data)
      this.groceryList = promise.data;
      console.log(this.groceryList);
      this.cdr.markForCheck();
    })
  }

  deleteGroceryRecipeById(recipeId){
    this.recipeService.deleteGroceryRecipeById(recipeId).subscribe(promise=>{
      this.refreshGroceryList();
    });
  }


  public trackByIdCode(index: number, grocery: any): string {
    console.log("tracking");
    return grocery._id;
}

  ngOnInit(): void {
  }

  recipeService;
  groceryList: object[];
  showFiller=false;
}

而且我不能使用 changeDetection: ChangeDetectionStrategy.OnPush 因为当我什么都不做时显示在我的 dom 中并且我不知道为什么但是当我切换到 changeDetection: ChangeDetectionStrategy.Default 时,事情再次显示但仍然没有更新。

编辑:我什至尝试了一个更简单的 html,但它仍然没有随着更改而更新。这是我的简单html:

<p *ngFor="let grocery of groceryList;trackBy:trackByCode;">{{grocery.recipeName}}</p>

我真的很希望有人看到这里发生了什么,因为我完全不知所措。我不知道我还能做什么

标签: javascripthtmlangular

解决方案


由于 trackBy,它没有更新 - 我只是点击了这个。我正在使用 onPush 和 trackBy 导致缓存问题。我还没有完全解开它,但 trackby 是我没有得到更新的原因(在我的情况下,它只是对大型集合中单个复杂对象的 attr 的更新)

在您的 trackBy 函数中,返回更新值的字符串表示形式,并将其与索引或其他唯一值相关联。


推荐阅读