【问题标题】:Implementing if else condition inside a mat-cell of a mat-table - Angular 5在 mat-table 的 mat-cell 内实现 if else 条件 - Angular 5
【发布时间】:2019-06-04 13:59:53
【问题描述】:

我正在尝试在我的 Angular 应用程序中的 mat-table 的 mat-cell 内实现 if else 条件。但我从控制台收到错误“错误错误:StaticInjectorError(AppModule)[NgIf -> TemplateRef]:”

我的代码是

<ng-container matColumnDef="role">
    <mat-header-cell *matHeaderCellDef>Role</mat-header-cell>        
    <mat-cell *matCellDef="let user" ngIf="{{user.roles.length == 1}}">
        Admin          
    </mat-cell>
  </ng-container>

非常感谢任何帮助。

【问题讨论】:

    标签: angularjs typescript angular5 mat-table


    【解决方案1】:

    你有ngIf,但它应该以星号为前缀:*ngIf

    此外,使用*ngIf 之类的绑定指令属性,您不需要在其中使用花括号。只是做*ngIf="user.roles.length == 1" 应该没问题。

    但是,通常你不能在同一个元素上使用两个带有星号的指令,因此使用另一个 &lt;ng-container&gt; 可能是解决此问题的方法:

    <ng-container matColumnDef="role">
      <mat-header-cell *matHeaderCellDef>Role</mat-header-cell>
      <ng-container *ngIf="user.roles.length == 1">
        <mat-cell *matCellDef="let user" >
          Admin          
        </mat-cell>
      </ng-container>
    </ng-container>
    

    【讨论】:

    • 谢谢,但这不起作用,因为在 ng-container 中未定义“用户”
    • 啊,是的,也许只是切换这两个元素的顺序。无论如何,您都必须使用 2 个元素,因为您有两个使用 * 的指令,并且每个元素只能有一个。
    【解决方案2】:

    我也遇到过同样的问题。我想出了以下解决方案。

    1. 您可以使用[ngClass],如下所示。
      <tr mat-footer-row [ngClass]="dataSource.length==0 ? 'hide' : ''" *matFooterRowDef="displayedColumns1"></tr>
    
    1. 或者如果你想隐藏一些单元格,你可以使用[hidden]属性。这就像 CSS 的“display: none”属性。
      <tr mat-footer-row [hidden]="dataSource.length==0" *matFooterRowDef="displayedColumns1"></tr>
    

    【讨论】:

      【解决方案3】:

      您可以使用一个类将显示设置为无,这样就可以了

      <ng-container matColumnDef="role">
      <mat-header-cell *matHeaderCellDef>Role</mat-header-cell>        
      <mat-cell *matCellDef="let user" [ngClass]="'hide':user.roles.length == 1">
          Admin          
      </mat-cell>
      

      在你的样式表文件中

      .hide {
        display: none;
      }
      

      【讨论】:

        【解决方案4】:

        添加包装器ng-container 可以在父容器上获取​​user 对象并在*ngIf 的子容器中使用该paren 访问变量。

        
            <ng-container matColumnDef="role">
              <th *matHeaderCellDef mat-header-cell>Role</th>
              <td *matCellDef="let user" mat-cell>
                <ng-container *ngIf="user.roles.length == 1;else conditionNotMet">
                  Admin (Condition is met)
                </ng-container>
              </td>
        
              <ng-template #conditionNotMet>
                What ever logic...
              </ng-template>
            </ng-container>
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-05-12
          • 1970-01-01
          • 2019-12-05
          • 2021-06-10
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-08-22
          相关资源
          最近更新 更多