【问题标题】:Read content from an array in Angular从 Angular 中的数组中读取内容
【发布时间】:2021-04-22 18:01:37
【问题描述】:

我想输出不同英寸尺寸的自行车。为此,我有一个带有数组的 json 文件。

[{
"name": "Mountainbike",
"img_url": "assets/img/mountainbike.jpg",
"mount_size": [{"mount_s": "26"},
                {"mount_s": "26"}]}]

在我的组件中,我调用了 json 文件

bike.component.ts

 export class BikeSelectComponent implements OnInit {
  biketypes: Biketype[] = [];

  constructor(private apiService: ApiService) {
    this.apiService
      .getBikes()
      .subscribe((biketypes) => (this.biketypes = biketypes));
  }

  ngOnInit(): void {}
}

我想为每英寸尺寸生成一个额外的按钮。我该怎么做?

bike.component.html

<div class="container" >
  <div class="row">
    <div class="col-12 "><h1>Welcome</h1></div>
  </div>
  <div class="row text-center">
    <div class="col" *ngFor="let biketype of biketypes">
      <figure>
        <img src="{{biketype.img_url}}" alt="" width="200px" height="200px">
        <figcaption class="bike-name">{{biketype.name}}</figcaption>
          <figcaption ><button class="btn-size">{{biketype.mount_size}} Zoll</button></figcaption>

      </figure>
    </div>
  </div>
</div>

【问题讨论】:

  • 2 个按钮用于 2 个 mount_s?
  • 每英寸大小的“mount_size”一个按钮。因此,一个 26 英寸的按钮和一个 28 英寸的按钮,例如
  • 在您的 json 中看不到 28 英寸。
  • 我相信 harleybl 的以下回答是正确的。
  • Aakash 对不起,我不小心在 2 次中写了 26。它应该是一次 26 和一次 28

标签: html json angular


【解决方案1】:

由于 mount_size 是一个数组,您需要另一个 *ngFor 来遍历 mount_size 数组并为每个大小创建按钮。这应该有效:

<div class="container" >
  <div class="row">
    <div class="col-12 "><h1>Welcome</h1></div>
  </div>
  <div class="row text-center">
    <div class="col" *ngFor="let biketype of biketypes">
      <figure>
        <img src="{{biketype.img_url}}" alt="" width="200px" height="200px">
        <figcaption class="bike-name">{{biketype.name}}</figcaption>
          <figcaption *ngFor="let mt_size of biketype.mount_size">
               <button class="btn-size">{{mt_size.mount_s}} Zoll</button>
          </figcaption>
      </figure>
    </div>
  </div>
</div>

【讨论】:

  • @Dominik Hard 也许您不需要每个尺寸的无花果标题。然后将*ngFor="..."移动到下面的&lt;button&gt;标签中
  • @harleybl 非常感谢。效果很好:)
  • @David B. 你是什么意思? :)
  • 以防万一您只需要 2 个按钮,但在 1 个 figcaption 中,而不是 2 个 figcaption,每个按钮都在里面。没关系它是否适合你。
猜你喜欢
  • 1970-01-01
  • 2018-10-26
  • 2016-02-21
  • 1970-01-01
  • 2018-01-03
  • 2014-11-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多