这是我在学习角材料时正在做的角材料项目上的代码。
问题是我试图从先前以表单保存的本地存储中获取数据,并通过mat-table呈现它。但是它不能正确渲染它。
错误:ERROR Error: "Could not find column with id "name"."
显然,我具有包含在对象中的名称列属性。我不明白为什么会发生此问题。
export interface Rec {
name: string;
cert: string;
cgpa: number;
}
const record: Rec[] = [] ;
// @title Dialog Overview
@Component({
selector: 'app-modal',
templateUrl: 'modal.component.html',
styleUrls: ['modal.component.scss'],
})
export class ModalComponent implements OnInit {
constructor(public dialog: MatDialog) {}
recs: Rec[] = [];
test() {
record.length = 0;
if (localStorage.reg) {
const reg = JSON.parse(localStorage.getItem('reg'));
// Getting data from two array to one from localstorafe
for (let index = 0; index < reg.length; index++) {
const pat = JSON.parse(localStorage.getItem(reg[index]));
const patQ = JSON.parse(localStorage.getItem(reg[index] + 'Q'));
const data = {
name: pat.sal + ' ' + pat.fname + ' ' + pat.lname,
cert: patQ.cert1,
cgpa: patQ.cgpa1,
};
record.push(data);
}
this.recs = record;
}
console.log(record);
}
ngOnInit() {
this.test();
console.log(this.recs);
}
openDialog() {
const dialogRef = this.dialog.open(Modal);
}
}
<!-- modal.component.html -->
<table mat-table #table [dataSource]="recs">
<ng-container cdkColumnDef="name">
<th mat-header-cell *cdkHeaderCellDef> Name </th>
<td mat-cell *cdkCellDef="let row"> {{row.name}} </td>
</ng-container>
<ng-container cdkColumnDef="cert">
<th mat-header-cell *cdkHeaderCellDef> Certification </th>
<td mat-cell *cdkCellDef="let row"> {{row.cert}} </td>
</ng-container>
<ng-container cdkColumnDef="cgpa">
<th mat-header-cell *cdkHeaderCellDef> C/GPA </th>
<td mat-cell *cdkCellDef="let row"> {{row.cgpa}} </td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="['name', 'cert', 'cgpa']"></tr>
<tr mat-row *matRowDef="let row; columns: ['name', 'cert', 'cgpa'];"></tr>
</table>
答案 0 :(得分:0)
在命名列属性时看不到问题。 但是请尝试以下更改,让我知道错误仍然存在。
import { MatDialog, MatTableDataSource } from '@angular/material';
const record: any = [];
export class ModalComponent implements OnInit {
constructor(public dialog: MatDialog) {}
recs: any;
test() {
record.length = 0;
if (localStorage.reg) {
...
this.recs = new MatTableDataSource<Rec>(record);
}
}
}
答案 1 :(得分:0)
我会做这样的事情:
var data = localStorage.getItem('data'); // Get the data first
if (data) { // If data is available then parse it and assgined as `MatTableDataSource`
var parsedData = JSON.parse(localStorage.getItem('data'));
this.recs = new MatTableDataSource(parsedData);
}
else { // Otherwise set first and then use
localStorage.setItem('data', JSON.stringify(ELEMENT_DATA));
var parsedData = JSON.parse(localStorage.getItem('data'));
this.recs = new MatTableDataSource(parsedData);
}
答案 2 :(得分:0)
几个小时后我找到了自己的解决方案。
在HTML文件的每一行上用“ mat”替换了“ cdk”。桌子被完美地渲染了。