【问题标题】:Show Json object properties显示 Json 对象属性
【发布时间】:2021-12-02 10:43:08
【问题描述】:

在我的应用程序中,我有 json 数组,我可以显示这些数据。所有数据都有单选按钮。我想要的是当我单击单选按钮时,该 json 数组项的数据将以 html 格式打印在另一个组件中。像下面的东西。 This is how it is showing

下面有我的 product.component.ts。

ngOnInit() {
   this.wordpressService.apiCall().subscribe((data)=>{
     console.warn("get api data ",data);
     this.title=data;
   })
}
radioHandle(event : any){
     this.post=event.target.value;
  }

然后在我的 product.component.html 中显示一些 json 数据,如下所示。

<div class='container'>
  <div id="leftDiv">
   <div *ngFor="let data of title">
    <p>
      <input type="radio"
      name="posts"
      value="{{data | json}}"
      (change)="radioHandle($event)">
      {{data.id}}
    </p>
  </div>
</div>
<div id="rightDiv">
  <app-productDisplay [parentData]=post></app-productDisplay>
</div>
</div>

现在我想将选定的数据传递给另一个名为 productDisplay.component.ts 的组件

 @Input() public parentData: any;

并在productDisplay.component.html中显示数据

{{parentData}}

它有效。但问题是它是显示 json 对象。但我想打印 json 对象的一些属性而不是整个 json

【问题讨论】:

  • 也许{{parentData | json}} 会有所帮助
  • @EMilen 它显示 json 数据。我想单独打印属性。类似于 parentData.Id 的东西。但它不起作用

标签: json angular


【解决方案1】:

您是否尝试过 JSON.parse()?我想这可以做到你所描述的。

在您的 productDisplay.component.ts 中:

let parentDataParsed = JSON.parse(parentData)

在你的模板中:

{{parentDataParsed.Id}}

【讨论】:

  • 你能告诉我在 productDisplay.component.ts 的什么地方使用它
  • 如果您不需要 json 字符串来做其他任何事情,我会将它放在 product.component.ts 的订阅部分中,并将它作为已解析的输入传递给 productDisplay 组件。因此,在产品组件中的 ngOnInit() 中,类似于...subscribe((data)=&gt;{ ... this.parentDataParsed = JSON.parse(data) ... }),而不是将 parentData 作为输入传递,而是传递已经解析的 parentDataParsed。或者我猜 productDisplay.component.ts 中的构造函数可以做到。
  • @Dinithi 需要帮助还是需要更多帮助?
  • 我没试过。由于我是角度新手,所以我不知道如何使用它。
【解决方案2】:

必须先在 product.component.ts 中解析 JSON

ngOnInit() {
   this.wordpressService.apiCall().subscribe((data)=>{
     console.warn("get api data ",data);
     this.parentDataParsed = JSON.parse(data)
   })
}

通过数据绑定将数据传递给productDisplay组件

<app-product-display [parentData]="parentDataParsed"></app-product-display>

在productDisplay组件中,可以显示个别字段

<p>ID: {{parentData?.id}}</p>
<p>TITLE: {{parentData?.title}}</p>
....

【讨论】:

    猜你喜欢
    • 2019-12-01
    • 2016-09-17
    • 2013-04-20
    • 2015-05-17
    • 1970-01-01
    • 2017-09-13
    • 2018-01-29
    • 2021-03-12
    • 1970-01-01
    相关资源
    最近更新 更多