-1

Lets say I have 2 tables; Book and Author. The Author table holds a reference to the ID of a book.

In Angular I would like to loop through the Authors and then loop through the books of that Author:

<div id="authors" *ngFor="let author of authors">
    <h1>{{author.name}}</h1>

    <div id="books" *ngFor="let book_id of author.books" ng-init="let book = getBook(book_id)">
        <h2>{{book.title}}</h2>
        .....
    </div>

</div>

The issue here is that ng-init is not in Angular 2+. I need to be able to run a function to be able to get the book from the database as the Author only holds a reference to the book.

I've seen a couple of potential solutions that use custom directives. 1 2.

My question is, what is best practice in this scenario? Or is the scenario the issue, wherein I should be handling the data better at an earlier stage? My reason for doing it this way, is if i do not need books of certain genre, I can hide (using ngIf) them without ever needing to call the DB to get the book (so more efficient?).

I'm questioning the directives solution a bit as i'm surprised this is not built into Angular as it seems like a potentially common problem, unless there is a better solution they want you to use.

Waddas
  • 1,353
  • 2
  • 16
  • 28

1 Answers1

0

You can use "ngIf" like show in https://alligator.io/angular/ngif-new-features-angular4/

<div id="authors" *ngFor="let author of authors">
    <h1>{{author.name}}</h1>
    <div id="books" *ngFor="let book_id of author.books">
       <ng-container *ngIf="getBook(book_id);let book">
        <h2>{{book.title}}</h2>
        .....
       <ng-container>
    </div>
</div>

but choose between this idea and transform the array

Eliseo
  • 50,109
  • 4
  • 29
  • 67