Search code examples
arraysangularangular2-components

Understand first for result Angular2 ngFor


I have an array multidimensional with multiples results:

books: any[] = [
    {
    name: "The Name book",
    chapter: [{
        name: 'Alpha',
        pages: '180'
    }, {
        name: 'Beta',
        pages: '100'
        }]
    },
    {
    name: "Jungle Book",
    chapter: [{
        name: 'Whole book',
        pages: '300'
    }]
    }
]

I would like to understand how to create a *ngIf when a book has just one chapter like "Jungle book" or multiples as "The Name Book."

Thanks for your help


Solution

  • I am not sure I have fully understood the selection creteria.

    Anyway, assuming the template where you want to add the *ngIf check is defined in the same Component where you define the books property, I would try something like this

    In the template

    <div *ngFor="let book of books">
      <div *ngIf="isBookToShow(book)">
        <!-- here goes the rest of your html -->
      </div>
    </div>
    

    with the corresponding method isBookToShow(book) in the class

    isBookToShow(book) {
      return book.chapter.length > 0
    }