【问题标题】:Hide mat-table column if formfield has no value如果表单字段没有值,则隐藏 mat-table 列
【发布时间】:2021-11-11 07:45:16
【问题描述】:

我是编程领域的新手,并且正在处理带有用于过滤的表单字段的表格。
如果表单字段有值,我想隐藏或显示表格列。

所以在我的 table.component.ts 中:

 form:FormGroup = new FormGroup({
titleFormControl: new FormControl('')})

然后我像这样声明列:

columns = [
{
  columnDef: 'title',
  header: 'Titel',
  cell: (element: Movie) => `${element.title}`,
  hide: false,
}];
displayedColumns = this.columns.map(c => c.columnDef);

table.component.html

<form [formGroup]="form">
<mat-form-field appearance="fill">
  <mat-label>Titel</mat-label>
  <input type="text" matInput  #titleFormControl placeholder="Titel">
</mat-form-field></form>

<mat-table #table [dataSource]="movies" class="mat-elevation-z8">
  <ng-container *ngFor="let column of columns" [matColumnDef]="column.columnDef">
    <th mat-header-cell *matHeaderCellDef hidden="column.hide">>
      {{column.header}}
    </th>
    <td mat-cell *matCellDef="let row" hidden="column.hide">
      {{column.cell(row)}}
    </td>
  </ng-container>
  <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
  <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</mat-table>

如果 titleFormControl 有值,我如何显示该列。
或者如何更新列数组字段隐藏和刷新表格。
我目前一无所知,如果有任何帮助,我将不胜感激。

【问题讨论】:

    标签: angular typescript angular-material angular-forms mat-table


    【解决方案1】:

    每个 FormControl 都有一个值,您可以使用 value 属性轻松读取该值。

    https://material.angular.io/components/form-field/api#MatFormFieldControl

    我相应地更改了您的示例,而不是将列的 hide 属性设置为 false,而是将其设置为 titleFormControl 的值:

    columns = [
    {
      columnDef: 'title',
      header: 'Titel',
      cell: (element: Movie) => `${element.title}`,
      hide: this.titleFormControl.value
    }];
    displayedColumns = this.columns.map(c => c.columnDef);
    

    还有example如何使用FormControl值隐藏表格列。

    【讨论】:

    • 谢谢。有效
    猜你喜欢
    • 1970-01-01
    • 2019-04-07
    • 1970-01-01
    • 2013-10-02
    • 1970-01-01
    • 1970-01-01
    • 2016-09-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多