【问题标题】:Angular Material Table - how to place *ngIf on whole column?角材料表 - 如何将 *ngIf 放在整个列上?
【发布时间】:2022-01-24 21:13:17
【问题描述】:

我有一个 Angular 材料表,并希望在整个列上放置一个 ngIf,以便整个列、标题和数据单元格仅在条件为真时显示。我可以将它放在数据单元格上,但我似乎不知道如何将它放在 ng-container 或 mat-h​​eader-cell 上。

我尝试使用 ngFor,然后使用 ngIf,我尝试将标题包装在 div 或表标题 & 行中,但没有成功。

result 是对象,具有 websiteUrl 属性


<table mat-table matSort [dataSource]="dataSource">
    
    <ng-container matColumnDef="websiteUrl">
        <th mat-header-cell *matHeaderCellDef mat-sort-header>Website Link</th>
        <td mat-cell *matCellDef="let result">
            <div *ngIf="showWebsiteLink===1">
                <div *ngIf="websiteLinkVisible(result)">
                    <a (click)="copyLink(result.websiteUrl)">
                        Copy Link
                    </a>
                </div>
            </div>
        </td>
    </ng-container>

    <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
    <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>

</table>

【问题讨论】:

    标签: html angular html-table angular-material


    【解决方案1】:

    我为你做了一个非常简单的例子。要删除整个 col,您需要在 someCondition 为 false 时使用 *ngIf 将其从模板中删除。而且您还需要从 displayedColumns 数组中删除相同的列名。后者更为重要。在示例中,我删除了 col 'weight'。

    @Component({
      selector: 'my-app',
      templateUrl: './app.component.html',
      styleUrls: [ './app.component.css' ]
    })
    export class AppComponent  {
      name = 'Angular 5';
      displayedColumns = ['position', 'name', 'weight', 'symbol'];
      dataSource = new MatTableDataSource<Element>(ELEMENT_DATA);
      someCondition: boolean = false;
      
      constructor() {
        if (!this.someCondition) {
          this.displayedColumns.splice(2,1);
        }
      }
    }
    

    https://stackblitz.com/edit/angular-material-table-data-source-kdttsz?file=app%2Fapp.component.ts

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-20
      • 1970-01-01
      • 2019-11-22
      • 1970-01-01
      • 2022-08-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多