如果表单字段没有值,则隐藏 mat-table 列
Posted
技术标签:
【中文标题】如果表单字段没有值,则隐藏 mat-table 列【英文标题】:Hide mat-table column if formfield has no value 【发布时间】: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 有值,我如何显示该列。 或者如何更新列数组字段隐藏和刷新表格。 我目前一无所知,如果有任何帮助,我将不胜感激。
【问题讨论】:
【参考方案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值隐藏表格列。
【讨论】:
谢谢。有效以上是关于如果表单字段没有值,则隐藏 mat-table 列的主要内容,如果未能解决你的问题,请参考以下文章
使用angular js根据下拉列表中的选定输入隐藏表单中的字段
使用来自 javascript 的返回值自动填充隐藏的表单字段