Reputation: 35
I have a project and frontend was developed via @angular/cli: 1.1.3
. Everything worked fine until I had tried compile the project in prod mode(ng build -prod
). At places where I used *ngFor
directive with trackBy
token I got the error like this
...src/app/app.component.ts.AppComponent.html (4,11): Property 'p' does not exist on type 'AppComponent'.
If I remove 'trackBy' statement error will disappear. I've repeated this error in blank project to attach it here.
AppComponent class declaration:
import {Component, OnInit} from '@angular/core';
import {Observable} from "rxjs/Rx";
@Component({
selector: 'app-root',
template: `
<ul>
<li *ngFor="let p of ppp | async;trackBy: p?.s">
<h2>{{p.s}}</h2>
</li>
</ul>`,
})
export class AppComponent implements OnInit {
ppp: Observable<any[]>;
constructor() {
}
ngOnInit() {
this.ppp = Observable.create((observer) => {
observer.next([{s: "0"}]);
setTimeout(function () {
observer.next([{s: "1"}, {s: "2"}, {s: "3"}]);
}, 2000);
});
}
}
AppModule class declaration:
import {BrowserModule} from '@angular/platform-browser';
import {NgModule} from '@angular/core';
import {AppComponent} from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule {
}
Is there an approach to call successfully ng build -prod
and keep trackBy statements;
Upvotes: 3
Views: 3742
Reputation:
trackBy
must be a function-valued property on the component. Read the documentation, which is perfectly clear.
Add a method to the component that returns the value
NgFor
should track.
<li *ngFor="let p of ppp | async; trackBy: trackByS">
<h2>{{p.s}}</h2>
</li>
public trackByS(p) { return p.s; }
The trackBy
part of your code did not actually do what you thought it, even when not compiling with AoT. trackBy: p?.s
tried to access a property p
on the component, which does not exist, so it was ignored. It's just that AoT compiles the template logic, which exposed the error.
Upvotes: 13