Angular列出全部或按类别列出

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>

我有一个工作代码... 它显示带有类别的项目, 但我想显示所有不检查类别的项目,当 cat==all 我不想复制这段代码

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

获取所有项目,而是在同一个 div 中实现一些逻辑 里面的所有选项。

喜欢:全部,分类名称,分类名称...

只需使用 OR 条件,

    <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>

您应该改为创建过滤器 pipe。然后你的过滤逻辑从模板中抽象出来,你可以在你认为合适的未来修订中扩展它。不要忘记将它包含在 @NgModule 中的 declarations 中。

Working StackBlitz

categoryFilterPipe.ts

import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
    name: 'categoryFilter',
    pure: false
})
export class CategoryFilterPipe implements PipeTransform {
    transform(books: {category:string}[], category:string): any {

        return (category && category !== 'all')
            ? books.filter(_ => _.category === category)
            : books;
    }
}

html模板

<div *ngFor="let book of books | categoryFilter : cat">
  <h3>{{book.title}}</h3>
  <h4>{{book.author}}</h4>
</div>