我正在使用Angular mat表创建一个简单的三列表格。在它中,我需要隐藏2列时,单击表中的任何行。所以我创建了一个click函数,并在单击行时将boolean变量设置为true。
通过使用该布尔值,我在HTML文件中添加了*ngIf条件,以便在行单击时隐藏列。但是*ngIf在角垫表中不起作用。
下面是我的代码:
HTML
<table mat-table [dataSource]="dataSource" class="mat-elevation-z8">
<ng-container matColumnDef="name">
<th mat-header-cell *matHeaderCellDef> Dessert (100g)</th>
<td mat-cell *matCellDef="let element"> {{element.name}} </td>
</ng-container>
<ng-container *ngIf="rowClick" matColumnDef="calories">
<th mat-header-cell *matHeaderCellDef>Calories</th>
<td mat-cell *matCellDef="let element"> {{element.calories}} </td>
</ng-container>
<ng-container *ngIf="rowClick" matColumnDef="fat">
<th mat-header-cell *matHeaderCellDef>Fat (g)</th>
<td mat-cell *matCellDef="let element"> {{element.fat}} </td>
</ng-container>
<ng-container *ngIf="rowClick" matColumnDef="carbs">
<th mat-header-cell *matHeaderCellDef>Carbs (g)</th>
<td mat-cell *matCellDef="let element"> {{element.carbs}} </td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;" (click)="rowClicked()"></tr>
</table>TS
export class sampleComponent implements OnInit {
public rowClick: boolean =true;
constructor() { }
ngOnInit(): void {
}
public rowClicked() {
this.rowClick = false;
console.log(this.rowClick);
}
dataSource: Food[] = [
{name: 'Yogurt', calories: 159, fat: 6, carbs: 24},
{name: 'Sandwich', calories: 237, fat: 9, carbs: 37},
{name: 'Eclairs', calories: 262, fat: 16, carbs: 24},
{name: 'Cupcakes', calories: 305, fat: 4, carbs: 67},
{name: 'Gingerbreads', calories: 356, fat: 16, carbs: 49},
];
displayedColumns: string[] = ['name', 'calories', 'fat', 'carbs'];
}发布于 2020-07-27 02:45:16
您可以修改displayedColumns变量来控制呈现哪些列,而不是使用*ngIf指令。请尝试以下操作
export class sampleComponent implements OnInit {
...
displayedColumns: string[] = ['name', 'calories', 'fat', 'carbs'];
public rowClicked() {
this.displayedColumns = ['name'];
}
public reset() {
this.displayedColumns = ['name', 'calories', 'fat', 'carbs'];
}
}现在不需要rowClick布尔标志了。
https://stackoverflow.com/questions/63104176
复制相似问题