如何修复 Angular NG0303: Can't bind to 'ngForTrack' since it isn't a known property of ...

问题

在浏览器中打开 Angular 应用时,你看到如下错误消息

ng0303_error_example.txt
my.component.html:14 NG0303: Can't bind to 'ngForTrack' since it isn't a known property of 'div' (used in the '_MyComponent' component template).
1. If 'div' is an Angular component and it has the 'ngForTrack' input, then verify that it is included in the '@Component.imports' of this component.
2. To allow any property add 'NO_ERRORS_SCHEMA' to the '@Component.schemas' of this component.

解决方案

首先,确保在你使用 ngFor="... ; trackBy ... 的模块中将 NgFor 添加到 imports 数组:

import_ngfor.ts
import { NgFor } from '@angular/common';

@Component({
  imports: [
    // ...
    NgFor,
    // ..
  ],
})
// ...

但是,此错误最常见的来源之一是错误的语法:track by myTrackFunction

需要这样使用:

ngfor_trackby_example.html
<div *ngFor="let item of items; trackBy: myTrackFunction">

所以使用 trackBy: myTrackFunction,其中 trackBy(无空格)后跟一个冒号:),然后是你的跟踪函数的函数名!


Check out similar posts by category: Angular, Typescript