【问题标题】:How to filter ngFor table rows with radio-button dynamically如何使用单选按钮动态过滤 ngFor 表行
【发布时间】:2020-02-08 18:34:47
【问题描述】:

我的 .ts 文件中有两 (2) 个函数,用于按日期过滤 ngfor 表的两 (2) 个不同的单选按钮。这两个按钮称为:“有效”和“无效”。 “无效”单选按钮过滤表格并显示结束日期“小于当前日期”的所有行,而“有效”显示所有结束日期“小于和大于当前日期”的行。

刚才当我单击其中一个单选按钮时,我得到了正确的行,但是当我继续单击第二个单选按钮时,我得到了空行或零行。

无论是否按下单选按钮,如何完成 .ts 代码以使表格行可用(动态)?以下是我的代码:

.html

<div class="mb-3">
        <div class="form-check">
            <input class="form-check-input" type="radio" name="date" (click)="valid()" />
            <label class="form-check-label">Valid</label>
        </div>
        <div class="form-check">
            <input class="form-check-input" type="radio" name="date" (click)="invalid()"/>
            <label class="form-check-label">Invalid</label>
        </div>
</div>

<tr *ngFor="let myAccount of Account | filterBy: accountFilter | paginate: { itemsPerPage: count, currentPage: p }; let i = index">
            <td>{{ (p - 1) * count + i + 1 }}</td>
            <td>{{myAccount.name}}</td>
            <td>{{myAccount.startDate}}</td>
            <td>{{myAccount.endDate}}</td>
</tr>

.ts

Account = [];
currentDate = '';

valid() {
        this.currentDate = this.datePipe.transform(new Date(),"yyyy-MM-dd");
        this.Account = this.Account.filter(data => {
            return data.startDate < this.currentDate  && data.endDate > this.currentDate});
    }

invalid() {
    this.currentDate = this.datePipe.transform(new Date(),"yyyy-MM-dd");
    this.Account = this.Account.filter(data => {
        return data.startDate < this.currentDate  && data.endDate <= this.currentDate});
}

我该如何做才能让我的 Account = [ ] 仍然保留所有表格行,而我只是使用单选按钮根据日期过滤或切换行?

即使我以后应该添加第三个名为“ShowAll”的单选按钮,它也可以返回表中的所有行。

谢谢

【问题讨论】:

  • 你能在stackblitz.com复制它吗?
  • @PranavCBalan 我需要类似的东西:stackblitz.com/edit/… 但现在带有单选按钮...
  • 在 stackblitz 中分享您的代码以及一些重现问题的虚拟数据

标签: angular radio-button ngfor


【解决方案1】:

在 HTML 文件中使用 change 事件而不是 click

<div class="mb-3">
        <div class="form-check">
            <input class="form-check-input" type="radio" name="date" (change)="valid($event)" />
            <label class="form-check-label">Valid</label>
        </div>
        <div class="form-check">
            <input class="form-check-input" type="radio" name="date" (change)="invalid($event)"/>
            <label class="form-check-label">Invalid</label>
        </div>
</div>

<tr *ngFor="let myAccount of Account | filterBy: accountFilter | paginate: { itemsPerPage: count, currentPage: p }; let i = index">
            <td>{{ (p - 1) * count + i + 1 }}</td>
            <td>{{myAccount.name}}</td>
            <td>{{myAccount.startDate}}</td>
            <td>{{myAccount.endDate}}</td>
</tr>

【讨论】:

  • 我尝试了更改事件,但结果仍然相同.. 像这样:stackblitz.com/edit/… 是我需要的,但带有单选按钮
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多