Search code examples
angularlistangular-ng-if

Angular list all or according to the category


books=[{
    title:"Life is good",
    author:"benny",
    category:"life"
    },{
    title:'Canned in',
    author:"francis",
    category:"style"
  }];

<ng-container *ngFor="let book of books">
 <div *ngIf="book.category == cat">
  <h3>{{book.title}}</h3>
  <h4>{{book.author}}</h4>
 </div>
</ng-container>

I have a working code... it displays the item with the category, but I want to display all the item not checking the category, when cat==all I do not want to duplicate this code

<div *ngIf="book.category == cat">
 <h3>{{book.title}}</h3>
 <h4>{{book.author}}</h4>
</div>

to get all items, but rather implement some logic in the same div to have all the options in it.

Like: all, category name, category name...


Solution

  • Just use an OR condition,

        <ng-container *ngFor="let book of books">
            <div *ngIf="cat=='all' || book.category==cat">
                <h3>{{book.title}}</h3>
                <h4>{{book.author}}</h4>
            </div>
        </ng-container>