代码之家  ›  专栏  ›  技术社区  ›  SBB

角度-如果满足条件,则在ngfor中隐藏表格行

  •  2
  • SBB  · 技术社区  · 6 年前

    我有一个棱角分明的应用程序,它正在呈现一个员工详细信息表。有一个名为 Optional 这决定了它在默认情况下是否应该出现。

    我的目标是在默认情况下隐藏这些行,然后单击一个按钮就可以打开/关闭它们。

    例子:

    <table class="table table-condensed table-striped" *ngIf="s.fields">
       <tbody>
          <tr *ngFor="let f of s.fields.field" [class.hidden]="f.Optional == 1">
            <td>{{ f.FieldTitle }}</td>
            <td>{{ f.Value }}</td>
          </tr>
        </tbody>
    </table>
    

    到目前为止,我已经通过向行中添加一个类来正确地隐藏可选的行。

    我最终需要能够单击一个按钮来显示/隐藏这些隐藏行,但我不确定如何使用这种方法。

    我是使用CSS还是为它创建一个双向绑定或模型?

    2 回复  |  直到 6 年前
        1
  •  4
  •   dAxx_    6 年前

    state: boolean = false;
    
    isAllowed = (optional) => {
      return optional === 0 ? true : this.state;
    }
    
    changeState = () => {
      this.state = !this.state;
    }
    

    <table class="table table-condensed table-striped" *ngIf="s.fields">
       <tbody>
          <tr *ngFor="let f of s.fields.field">
            <ng-container *ngIf="isAllowed(f.Optional)">
              <td>{{ f.FieldTitle }}</td>
              <td>{{ f.Value }}</td>
            </ng-container>
          </tr>
        </tbody>
    </table>
    <br>
    <button (click)="changeState()">Show/Hide</button>
    
        2
  •  0
  •   monogate    6 年前

      s = {
        fields: {
          field: [
            {
              FieldTitle: 'field 1',
              Value: ' value 1',
              Optional: '1'
            },
            {
              FieldTitle: 'field 2',
              Value: ' value 2',
              Optional: '0'
            },
            {
              FieldTitle: 'field 3',
              Value: ' value 3',
              Optional: '1'
            },
            {
              FieldTitle: 'field 4',
              Value: ' value 4',
              Optional: '0'
            },
                    {
              FieldTitle: 'field 5',
              Value: ' value 5',
              Optional: '0'
            }
          ]
        }
      }
    

    click

    <table class="table table-condensed table-striped" *ngIf="!isToggled && s.fields">
       <tbody>
          <tr *ngFor="let f of s.fields.field">
            <td *ngIf="f.Optional == 1">{{ f.FieldTitle }}</td>
            <td *ngIf="f.Optional == 1">{{ f.Value }}</td>
          </tr>
        </tbody>
    </table>
    <br>
    <button (click)="onToggle()">toggle</button>
    

    isToggled false onToggle

    stackblitz.com