如何在 Angular 4 的 HTML 中包含或排除属性

Cod*_*erX 7 angular-material angular-material2 angular

我正在使用带有角度材料的 angular 4 来构建一张桌子。我希望在mat-sort-header以下模板上有条件地添加。

<mat-header-cell *matHeaderCellDef mat-sort-header>Id</mat-header-cell>
Run Code Online (Sandbox Code Playgroud)

我尝试了以下代码:

<mat-header-cell *matHeaderCellDef [mat-sort-header]=" column!='id' ? column : false ">Id</mat-header-cell>
Run Code Online (Sandbox Code Playgroud)

但它仍然在该列的表中添加排序标题。

我的整个表格如下所示,并且工作正常,除了排序标题问题:

  <mat-table #table1 [dataSource]="records" matSort class="mat-cell">

    <ng-container *ngFor="let column of keys" [matColumnDef]="column">
      <mat-header-cell *matHeaderCellDef [mat-sort-header]=" column!='actions' ? column : false ">
        <p *ngIf=" column!='actions' ">{{ column }}</p>
        <button *ngIf=" column=='actions' " mat-icon-button color="primary" (click)="functionA()">
          <mat-icon class="indigo-icon" aria-label="Example icon-button with a heart icon">add</mat-icon>
        </button>

      </mat-header-cell>
      <mat-cell *matCellDef="let row; let i=index;">
        <p *ngIf=" column!='actions' ">{{ row[column] }}</p>
        <button *ngIf=" column=='actions' " mat-icon-button color="accent" (click)="functionA()">
          <mat-icon class="indigo-icon" aria-label="Edit">edit</mat-icon>
        </button>

        <button *ngIf=" column=='actions' " mat-icon-button color="accent" (click)="functionA()">
          <mat-icon class="indigo-icon" aria-label="Delete">delete</mat-icon>
        </button>

      </mat-cell>
    </ng-container>

    <mat-header-row *matHeaderRowDef="keys"></mat-header-row>
    <mat-row *matRowDef="let row; columns: keys;"></mat-row>
  </mat-table>
Run Code Online (Sandbox Code Playgroud)

Cod*_*erX 15

好吧,我是这样解决的:

<mat-header-cell *matHeaderCellDef [mat-sort-header]=" column!='actions' ? column : null " [disabled]=" column=='actions' ? true : false " >
Run Code Online (Sandbox Code Playgroud)

需要绑定disabled属性。

  • 只有`[disabled]` 会这样做。无需有条件地删除“mat-sort-header”,因为在很多情况下会破坏排序 (4认同)

Dee*_*Raj 5

CoderX 的答案是解决您问题的最佳方法。但可能会出现需要根据条件呈现单独模板的情况。在这种情况下,您可以按照以下方式进行操作:

<ng-container *ngIf="column=='actions'; else noSort">
  <mat-header-cell *matHeaderCellDef mat-sort-header />          
</ng-container>

<ng-template #noSort>
  <mat-header-cell *matHeaderCellDef />         
</ng-template>
Run Code Online (Sandbox Code Playgroud)