angular - “找不到具有 id 的列...”尝试从 JSON 创建角度垫表时
问题描述
我很难从 JSON 创建动态生成的角度垫表。解释起来会有点复杂,因为我需要 4 个组件一起工作才能获得该表。该表将类似于此表的一般结构
它来自具有该结构的 Json(只有一个列和行元素以避免占用太多空间)
{"sessionID": "jdshfjksg12432dksfjl",
"mainObjectGUID": "lmmljlmfdkjgkj- hsqjkhgdkqj - sqsfdzeg",
"userGUID": "ushdshfjdfskjdshfjkdshkj",
"column": [{
"name": "ObjectGUID",
"accessJSON": "objectGUID",
"type": "String",
"visible": false,
"columnSize": null,
"dropdownList": null,
"controlType": null,
"control": null
},]
"rows": [{
"ObjectGUID": "djsklgfsdhjlk- fdhjhg - dkfsjgfl",
"columnName": "idCompany",
"Type": "Integer",
"primaryKey": true,
"Mandatory": true,
"updated": false
},]
}
我的问题是,我不能为表的每一列硬编码容器,因为它们包含不同类型的数据(文本、选择字段或复选框),并且随着 Json 的变化,所有内容都必须动态创建。所以我为三种情况(文本、选择字段和复选框字段)创建了 3 个子组件。现在我只想让文本数据工作。
这是我的主要组件
import {Component, OnInit} from '@angular/core';
// @ts-ignore
import mockData from '../../../assets/mock.json';
@Component({
selector: 'app-tab',
templateUrl: './tab.component.html',
styleUrls: ['./tab.component.scss']
})
export class TabComponent implements OnInit {
constructor() { }
displayedColumns: string[] =[];
dataSource: Array<any> = mockData.rows;
columnNames: string[] = [];
ngOnInit() {
this.createColumnNamesAndDisplayed();
}
click() {
console.log('data', this.dataSource);
}
createColumnNamesAndDisplayed(){
for (const col of mockData.column){
if (col.visible === true){
this.columnNames.push(col.name);
this.displayedColumns.push(col.accessJSON)
}
}
}
}
<table mat-table [dataSource]="dataSource" class="mat-elevation-z8" >
<app-str-container *ngFor="let x of displayedColumns" colId={{x}} colName="Test data"></app-str-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
我的文本容器组件
import { Component, OnInit, Input } from '@angular/core';
@Component({
selector: 'app-str-container',
templateUrl: './str-container.component.html',
styleUrls: ['./str-container.component.scss']
})
export class StrContainerComponent implements OnInit {
@Input() colName :string;
@Input() colId: string;
constructor() { }
ngOnInit() {
}
}
<ng-container matColumnDef={{colId}}>
<th mat-header-cell *matHeaderCellDef> {{colName}} </th>
<td mat-cell *matCellDef="let element"> {{element.colId}} </td>
</ng-container>
对我来说很奇怪,我一直收到来自 tab.component.html 的问题“无法找到 ID 为“columnName”的列,因为我以前遇到过这个问题,理解并解决了它。我对 Angular 很陌生,我“对绑定或@input 装饰器不太满意。如果您有另一种实现我想要的方法,请随时告诉我,我可能做错了。
解决方案
推荐阅读
- css - 如何将文本更改为白色?
- c++ - 竞争条件 2 个线程交替
- java - JavaFX 控制微调器不起作用
- javascript - 修改类的一个实例的属性时,该类的所有实例上的该属性都会更改
- javascript - 创建步行循环动画Javascript/CSS
- php - 如何正确使用 Scandir()?
- sql - SQL - 在别名上按 Max() 排序
- reactjs - 如何将 react-i18next 与连接的组件一起使用
- swift - 旋转 CollectionViewCell 后计算单元格偏移量
- bash - 计划在午夜运行的 BASH 脚本 cron - 每分钟运行一次,直到凌晨 12:20