angular-从JSON中读取属性名称作为列名称,并在列中显示另一个属性值

时间:2018-10-09 11:55:19

标签: json angular

我在结构中显示json文件(显示其对象之一)为

[
...
{
        "Tag": "YearOfOperation",
        "Type": 9,
        "Value": "2018"
    }
...
]

在html模板上,我有一张桌子。在表格的“运营年”行上,我要显示“ 2018”。我正在尝试遍历json(即按行/标签名查找)并显示json的显示“值”。在html模板中,我想输入以下内容:

<table>
<tr>
<td> Year Of Operation </td> // row name is hard coded. it doesn't depend on json
<td> display json "Value" where "Tag"=="YearOfOperation" </td>
</tr>
</table>

app.component.ts

public productData: any;


ngOnInit() {
            this.getJSON().subscribe(res => {
                this.productData = JSON.parse(res);
            })
        }

public getJSON(): Observable<any> {
        return this.http.get('./images/output_test.json')
            .pipe(
                map(res => res)
            )
        // .catch((error:any) => console.log(error));

    }

谢谢。

1 个答案:

答案 0 :(得分:0)

如果您的JSON如下所示,并且我正确理解了您的问题,那么这应该对您有用:

app.json

[
  { "Tag":"Location", "type": 9, "Value":"Europe" },
  { "Tag":"Location", "type": 10, "Value":"US" },
  { "Tag":"YearOfOperation", "type": 9, "Value":"2016" },
  { "Tag":"YearOfOperation", "type": 10, "Value":"2018" },
  { "Tag":"TaxId", "type": 9, "Value":"txn123" },
  { "Tag":"TaxId", "type": 10, "Value":"txn124" }
]

app.component.html

<table>
  <thead><tr><th>Location</th><th>Year Of Operation</th><th>Tax ID</th></tr></thead>
  <tbody>
    <tr *ngFor="let product of products">
      <td *ngIf="product?.Tag === 'Location'; else blankValue">{{product?.Value}}</td>
      <td *ngIf="product?.Tag === 'YearOfOperation'; else blankValue">{{product?.Value}}</td>
      <td *ngIf="product?.Tag === 'TaxId'; else blankValue">{{product?.Value}}</td>
    </tr>
  </tbody>
</table>
<ng-template #blankValue><td></td></ng-template>

app.component.ts

public products: any;

ngOnInit() {
    this.getJSON().subscribe(res => {
      this.products = <Array<{}>>res;
    })
}

public getJSON(): Observable<any> {
    return this.http.get('./images/output_test.json')
    .pipe(
      map(res => res),
      catchError((error) => { console.error(error); return error;})
    );
}

app.component.css

th {
    padding:10px;
    border:1px solid black;
}

td {
    padding:10px;
    border:1px solid black;
}