angular ngFor trackBy 无法按预期工作

标签 angular

当我阅读有关 ngFortrackBy 的文档 ( https://angular.io/api/common/NgForOf ) 时,我以为我明白 Angular 只会在 trackBy 返回值时重做 DOM功能改变了,但是当我在这里玩它时(https://stackblitz.com/edit/angular-playground-bveczb),我发现我实际上根本不明白它。这是我的代码的重要部分:

export class AppComponent {
  data = [
    { id: 1, text: 'one' },
    { id: 2, text: 'two' },
    { id: 3, text: 'three' },
  ];

  toUpper() {
    this.data.map(d => d.text = d.text.toUpperCase());
  }

  trackByIds (index: number, item: any) {
    return item.id; 
  };
}

和:

<div *ngFor="let d of data; trackBy: trackByIds">
  {{ d.text }}
</div>
<button (click)=toUpper()>To Upper Case</button>

我期望的是单击该按钮不会将列表从小写更改为大写,但确实如此。我以为我对 *ngFor 中的 trackBy 使用了 trackByIds 函数,因为 trackByIds 只检查id 项的属性,因此除 id 之外的任何更改都不应导致重做 DOM。我想我的理解是错误的。

最佳答案

如果trackBy似乎不起作用:

1) 确保您为 trackBy 函数使用了正确的签名

https://angular.io/api/core/TrackByFunction

interface TrackByFunction<T> {
  (index: number, item: T): any
}

您的函数必须将索引作为第一个参数,即使您只是使用该对象来派生“tracked by”表达式也是如此。

trackByProductSKU(_index: number, product: { sku: string })
{
    // add a breakpoint or debugger statement to be 100% sure your
    // function is actually being called (!)
    debugger;
    return product.sku;
}

2) 确保整个 控件(包含 *ngFor)没有被重绘,这可能是其他事情的副作用。

  • 添加<input/>在您的 *ngFor 正上方的控件中循环 - (是 - 只是一个空文本框)
  • 加载页面并在每个文本框中输入内容(我通常只输入 1、2、3、4...)
  • 从列表中添加/删除项目 - 或者您需要做的任何事情来触发更改
  • 如果文本框的内容消失,则意味着您正在重绘整个容器控件(换句话说,您的 trackBy 与您的基本问题无关)。
  • 你可以输入<input/>如果您有多个嵌套循环,则在每个“级别”。只需在每个框中键入一个值,然后查看在执行导致问题的任何操作时保留了哪些值。

3) 确保 trackBy函数为每一行返回一个唯一值:

<li *ngFor="let item of lineItems; trackBy: trackByProductSKU">

    <input />
    Tracking value: [{{ trackByProductSKU(-1, item) }}]
</li>

像这样在循环中按值显示轨道。这将消除任何愚蠢的错误——例如通过不正确的属性获取轨道的名称或外壳。空的input元素是故意的

如果一切正常,您应该能够在每个输入框中输入内容,触发列表中的更改,并且它不应该丢失您输入的值。

4) 如果您无法确定唯一值,只需退回商品本身。如果您不指定 trackBy 函数,这是默认行为(来自 trackByIdentity)。

// angular/core/src/change_detection/differs/default_iterable_differ.ts

const trackByIdentity = (index: number, item: any) => item;

export class DefaultIterableDiffer<V> implements IterableDiffer<V>, IterableChanges<V> {

 constructor(trackByFn?: TrackByFunction<V>) {
    this._trackByFn = trackByFn || trackByIdentity;
 }

5) 不要意外返回 null 或 undefined!

假设您正在使用 product: { sku: string }作为您的 trackBy 函数,无论出于何种原因,产品不再具有该属性集。 (也许它变成了 SKU 或者有一个额外的级别。)

如果你返回product.sku从您的函数中获取并且它为 null 那么您将得到一些意想不到的行为。

关于angular ngFor trackBy 无法按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56677135/

相关文章:

angular - 在 Angular 中设置全局时区

javascript - 你如何在 html 文件中创建一个其构造函数需要参数的组件?

angular - Firestore - 用于设置每个用户数据的逻辑收集模式?

javascript - 类型错误 : "ctx.cart is undefined"

angular 2 material matTooltip 多行

angular - 在 Azure Web 应用程序服务中部署 Angular 通用应用程序 - 基于 Linux

Angular ControlValueAccessor onChanges 不更新表单控件值

Angular 6 无法解析 'fs' 和 'path' 以使用 Electron

angularjs - 组件upperCaseComponent模板出错

angular - 由于错误 : Error: Module build failed: Error: ENOENT: no such file or directory, 打开,预呈现失败