首页 > 解决方案 > “找不到具有 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 装饰器不太满意。如果您有另一种实现我想要的方法,请随时告诉我,我可能做错了。

标签: angulartypescriptdata-bindingangular-materialmat-table

解决方案


推荐阅读