TrackById example #94
-
|
Hello, I'm trying to use the trackById directive in one of my angular components with a signal of type Array but even though I'm following the example which can be seen in the documentation I can't use it as expected, I get a syntax error even after importing the trackby-id-prop module. https://ngxtension.netlify.app/utilities/directives/trackby-id-prop/#trackbyid Any help would be appreciated, thanks in advance. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 4 replies
-
|
@iErKy Hi, can you provide a stackblitz? |
Beta Was this translation helpful? Give feedback.
-
|
Hi @iErKy I think that the problem you have is not due to trackById directive but the To fix the error in your specific case you can do something like this (if you know that you have an Observable that immediately emit values like const FAKEITEMS: ExampleItem[] =[
{ id: '1', name: 'item1' },
{ id: '2', name: 'item2' },
];
$items = toSignal(
of(FAKEITEMS), { requireSync: true } //<-- WITH THIS OPTIONS toSignal EXCLUDE THE undefined CASE
); //THIS WILL INFER Signal<ExampleItems[]> AND trackById WILL BE HAPPI AND WORKSIn other cases where you have an Observable that will emits first value async (like calling an http) you can fix the error passing an $items = toSignal(
http.get<ExampleItems[]>("/some-api"), { initialValue: [] as ExampleItems[] }
); //EVEN THIS WILL INFER Signal<ExampleItems[]> SO trackById MAY JUST WORKS ;-)Let's me know if with this suggestion you can use trackById and fix you errors 😉 |
Beta Was this translation helpful? Give feedback.

Hi @iErKy I think that the problem you have is not due to trackById directive but the
toSignalstictness.Becouse even if you are using an observable that will immediately emit the array, in you use-case the toSignal(ob$) has type: ExampleItem[] | undefined and this will generate the error on trakById that need all items to have a prop named
idthe undefined will fail this and generate error.To fix the error in your specific case you can do something like this (if you know that you have an Observable that immediately emit values like
of([item1, item2])