我正在使用Mat-Table以网格格式显示记录。我还通过使用两个不同的数据源实现了可扩展行。
第一个数据源将具有不重复的记录,当我单击一行时,它将展开并显示第二个数据源中具有重复记录的记录。我的要求是在展开的行中仅显示匹配的记录,但它显示第二个数据源中的所有记录。
我使用了* ngFor和* ngIf选项,但是它抛出错误。有人可以指导我确定正确的代码。
HTML代码:
<mat-table [dataSource]="mDataSource1" multiTemplateDataRows matSort>
<ng-container matColumnDef="Id">
<mat-header-cell *matHeaderCellDef mat-sort-header>Id</mat-header-cell>
<mat-cell *matCellDef="let element">{{element.Id}}</mat-cell>
</ng-container>
<ng-container matColumnDef="Name">
<mat-header-cell *matHeaderCellDef mat-sort-header>Name</mat-header-cell>
<mat-cell *matCellDef="let element">{{element.Name}}</mat-cell>
</ng-container>
<ng-container matColumnDef="Weight">
<mat-header-cell *matHeaderCellDef mat-sort-header>Weight</mat-header-cell>
<mat-cell *matCellDef="let element">{{element.Weight}}</mat-cell>
</ng-container>
<ng-container matColumnDef="expandedDetail">
<mat-table [dataSource]="mDataSource2" matSort>
<ng-container *ngIf = "element.Id === item.Id">
<ng-container matColumnDef="Id">
<mat-header-cell *matHeaderCellDef mat-sort-header>Id</mat-header-cell>
<mat-cell *matCellDef="let item">{{item.Id}}</mat-cell>
</ng-container>
<ng-container matColumnDef="Name">
<mat-header-cell *matHeaderCellDef mat-sort-header>Name</mat-header-cell>
<mat-cell *matCellDef="let item">{{item.Name}}</mat-cell>
</ng-container>
<ng-container matColumnDef="Weight">
<mat-header-cell *matHeaderCellDef mat-sort-header>Weight</mat-header-cell>
<mat-cell *matCellDef="let item">{{item.Weight}}</mat-cell>
</ng-container>
<mat-row *matRowDef="let row; columns: mDataSource2Columns;"></mat-row>
</ng-container>
</mat-table>
</ng-container>
<mat-header-row *matHeaderRowDef="mDataSource1Columns"></mat-header-row>
<mat-row *matRowDef="let row; columns: mDataSource1Columns;" class="example-element-row"
[class.example-expanded-row]="expandedElement === row"
(click)="expandedElement = expandedElement === row ? null : row"
(mouseover)="row.gridHovered = true" (mouseout)="row.gridHovered = false">
</mat-row>
<mat-row *matRowDef="let row; columns: ['expandedDetail']" class="example-detail-row"></mat-row>
<mat-footer-row *matFooterRowDef="['loading']" [ngClass]="{'hide':mDataSource1!=null}">
</mat-footer-row>
<mat-footer-row *matFooterRowDef="['noData']"
[ngClass]="{'hide':!(mDataSource1!=null && mDataSource1.data.length==0)}">
</mat-footer-row>
</mat-table>
mDataSource1 = [
{Id:1, name: 'ABC', weight: 40 },
{Id:2, name: 'DEF', weight: 45 },
{Id:4, name: 'GHI', weight: 85 }
]
mDataSource2 = [
{Id:1, name: 'ABC', weight: 10 },
{Id:1, name: 'ABC', weight: 14 },
{Id:1, name: 'ABC', weight: 16 },
{Id:2, name: 'DEF', weight: 23 },
{Id:2, name: 'DEF', weight: 22 },
{Id:4, name: 'GHI', weight: 44 },
{Id:4, name: 'GHI', weight: 41 }
]
当我单击第二行时,它应该在展开的行中仅显示2条记录,而不是所有记录。
ID Name Weight
2 DEF 23
2 DEF 22
我在您的示例中没有看到ngFor。Angular不允许在一个标签上使用多个结构指令。代替这个:
<div *ngIf="true" *ngFor="let..."></div>
使用此
<ng-container *ngIf="true">
<div *ngFor="let..."></div>
</ng-container>
不用担心ng-container,Angular不会将它放在DOM中。