【问题标题】:angular7 *ngFor with filterangular7 *ngFor 带过滤器
【发布时间】:2019-09-08 15:25:14
【问题描述】:

我怎样才能做到这一点?

ngFor 列表项应根据按钮单击更改,该项状态应为 true

*ngFor="let project of projects | conditionListTrueItem "

Json 示例

projects :
 { name:'name one', status: {
    ongoing: true,
    completed: false,
    incomplete: false,
} 
},
 { name:'name two', status: {
    ongoing: false,
    completed: true,
    incomplete: false,
} 
},
 { name:'name three', status: {
    ongoing: false,
    completed: false,
    incomplete: true,
} 
}

html

<button>Ongoing </button> 
<button>completed</button> 
<button>incomplete</button>

<div class="table" *ngFor="let project of projects">
<p>{{project.name}}</p>
</div>

project.ts

ngOnInit() {
    this.projectsService.getAllProjects().subscribe( response => {
      this.projects = response;
    })
  }

【问题讨论】:

  • 基于按钮,您需要设置一个值,并且您应该通过标准过滤器功能进行过滤,无需管道。 for 循环应该只用于显示。上述文章不是当前的推荐。

标签: html angular angular7 ngfor


【解决方案1】:

您的 json 模型效率不高。而是存储状态的值。

使用 ng-container 和 ngIf 指令

您还需要在 .ts 文件中为 selectedStatus 创建变量。

projects :
 { name:'name one', status: 'ongoing'
},
 { name:'name two', status: 'completed'
},
 { name:'name three', status: 'incomplete'
}
<button (click)="selectedStatus = 'ongoing'">Ongoing </button> 
<button (click)="selectedStatus = 'completed'">completed</button> 
<button (click)="selectedStatus = 'incomplete'">incomplete</button>

<ng-container class="table" *ngFor="let project of projects">
  <p *ngIf="project.status === selectedStatus">{{project.name}}</p>
</ng-container>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-23
    • 1970-01-01
    • 2021-08-12
    • 2019-07-16
    • 2018-02-26
    • 1970-01-01
    相关资源
    最近更新 更多