3

Angular 10, TypeScript: 3.9.7.

I'm trying to group a list of books by their CRN numbers. The "books" array is passed in the TextbooksComponent through @Input from a parent component.

My component.ts:

...
export class TextbooksComponent {
    @Input() books?: Array<Book>;
}
...

My component.html:

...
<div *ngFor="let book of books; let i=index" class="books">
    <div *ngIf="i>0 && book?.CRN === books[i-1]?.CRN; else bookCRN">
        <hr>
    </div>
    <ng-template #bookCRN>
        <h3>crn: {{ book?.CRN }}</h3>               
    </ng-template>
    <app-book
        [textbook]="book">
    </app-book>
</div>
...

I'm getting the following error when compiling, even after I use "?" to make my variables optional and checking i>0.

 ERROR in ...textbooks.component.html:16:42 - error TS2532: Object is possibly 'undefined'.

    16         <div *ngIf="i>0 && book?.CRN === books[i-1]?.CRN; else bookCRN">
                                                ~~~~~~~~~~

How do I fix this? I tried adding books?.length>1 too. It won't let me access the previous element in the array books[i-1]. I don't want to initialize and make up value for at least two elements in the books array. The data needs to be fetched from the server. Thanks.

Telly Ipock
  • 133
  • 3
  • 12
  • 2
    Did you try to remove `?` from `@Input() books?: Array;`? The error says that the array is possibly undefined, which `?` sign would suggest to compiler. – Pawel Kiszka Sep 15 '20 at 13:48
  • 2
    If I remove "?" from ```@Input() books?: Array;```, I get "Property 'books' has no initializer and is not definitely assigned in the constructor.ts(2564)" error message. – Telly Ipock Sep 15 '20 at 14:00
  • So I guess some answers from here might help: https://stackoverflow.com/q/49699067/7337369 – Pawel Kiszka Sep 15 '20 at 14:17

1 Answers1

3

You can get rid of the "possibly undefined" error by assigning default value to the input:

    @Input() books: Array<Book> = [];
mbojko
  • 13,503
  • 1
  • 16
  • 26