Angular Material@17.2.1表格报错:无法绑定'dataSource',尝试多种方法仍未解决
Angular Material@17.2.1表格报错:无法绑定'dataSource',尝试多种方法仍未解决
我仔细看了你的代码和遇到的问题,其实是几个关键细节没处理对,咱们一步步来解决:
1. 核心问题:Standalone组件的模块依赖错误
你的UsersComponent设置了standalone: true,这类组件需要自己导入所需的依赖模块,而不是依赖AppModule的导入。同时你在AppModule里错误地把UsersComponent加到了imports数组里,这会导致模块加载冲突。
修复步骤:
打开users.component.ts,在@Component装饰器里添加imports数组,导入表格所需的MatTableModule:
@Component({ selector: 'app-users', templateUrl: './users.component.html', styleUrl: './users.component.css', standalone: true, imports: [MatTableModule] // 新增这行,导入表格模块 })
然后打开app.module.ts,把imports数组里的UsersComponent移除(standalone组件不需要在NgModule的imports中声明):
imports: [ BrowserModule, AppRoutingModule, MatToolbarModule, MatSidenavModule, MatListModule, MatButtonModule, MatIconModule, MatTableModule, // UsersComponent, 删掉这一行 CdkTableModule ],
2. 模板属性绑定错误
你的模板里用了错误的属性名,比如element.position,但你的UserElement接口里根本没有position这个属性,对应关系完全不匹配。同时displayedColumns里的字段和接口字段也有大小写不一致的问题,需要统一修正:
第一步:修正接口和数据的字段名
打开users.component.ts,把接口里的firstname改成firstName(和displayedColumns里的字段统一),同时更新测试数据:
export interface UserElement { firstName: string; // 改成大写N,匹配displayedColumns lastName: string; email: string; microsoftEmail: string; class: string; } const ELEMENT_DATA: UserElement[] = [{ firstName: "Pierrick", // 同步修改字段名 lastName: "MARTELLIERE", email: "p.martelliere@gmail.com", microsoftEmail: "pierrick@coxidev.com", class: "GPME24" }];
第二步:修正模板里的绑定
打开users.component.html,把所有错误的属性绑定改成对应接口字段:
<table mat-table [dataSource]="dataSource" class="mat-elevation-z8 demo-table"> <ng-container matColumnDef="firstName"> <th mat-header-cell *matHeaderCellDef> Prénom </th> <td mat-cell *matCellDef="let element"> {{element.firstName}} </td> </ng-container> <ng-container matColumnDef="lastName"> <th mat-header-cell *matHeaderCellDef> Name </th> <td mat-cell *matCellDef="let element"> {{element.lastName}} </td> </ng-container> <ng-container matColumnDef="email"> <th mat-header-cell *matHeaderCellDef> Email </th> <td mat-cell *matCellDef="let element"> {{element.email}} </td> </ng-container> <ng-container matColumnDef="microsoftEmail"> <th mat-header-cell *matHeaderCellDef> Compte Microsoft </th> <td mat-cell *matCellDef="let element"> {{element.microsoftEmail}} </td> </ng-container> <ng-container matColumnDef="class"> <th mat-header-cell *matHeaderCellDef> Classe </th> <td mat-cell *matCellDef="let element"> {{element.class}} </td> </ng-container> <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr> <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr> </table>
做完这些修改后,重启你的Angular应用,应该就能正常显示表格了。
备注:内容来源于stack exchange,提问作者Pierrick Martellière
相关产品推荐
相关产品推荐

