如何使用* ngFor仅显示数组中的一项?

时间:2019-09-11 23:03:08

标签: angular

我在component.ts文件中创建了一个名为title的数组:

    this.projectInfo = {
      title: [
        'Title 1',
        'Title 2',
        'Title 3',
        'Title 4',
        'Title 5',
        'Title 6',
      ], 

我只想对模板中的每个“项目”使用该数组中的标题之一:

  <div class="item2">
    <img class="center" src="https://natureconservancy-h.assetsadobe.com/is/image/content/dam/tnc/nature/en/photos/tnc_48980557.jpg?crop=961,0,1928,2571&wid=600&hei=800&scl=3.21375">
    <h5 *ngFor="let projectTitle of projectInfo.title">{{projectTitle}}</h5>
    <p>{{ projectInfo.description }}</p>
  </div>
  <div class="item2">
    <img class="center" src="https://natureconservancy-h.assetsadobe.com/is/image/content/dam/tnc/nature/en/photos/tnc_48980557.jpg?crop=961,0,1928,2571&wid=600&hei=800&scl=3.21375">
    <h5 *ngFor="let projectTitle of projectInfo.title">{{projectTitle}}</h5>
    <p >{{ projectInfo.description }}</p>
  </div>
  <div class="item2">
    <img class="center" src="https://natureconservancy-h.assetsadobe.com/is/image/content/dam/tnc/nature/en/photos/tnc_48980557.jpg?crop=961,0,1928,2571&wid=600&hei=800&scl=3.21375">
    <h5 *ngFor="let projectTitle of projectInfo.title">{{projectTitle}}</h5>
    <p>{{ projectInfo.description }}</p>
  </div>

我要对第一个“项目”使用“标题1”,对第二个“项目”使用“标题2”,依此类推...

我尝试使用let i = index来帮助指定该数组中要使用的标题,但找不到如何做。

我对Angular还是很陌生,因此非常感谢您的帮助/指导。谢谢!

2 个答案:

答案 0 :(得分:0)

那又怎么样:

{{projectTitle[0]}}

用i替换0。 More here

答案 1 :(得分:0)

您将其放在整个块上并重复该块

<div class="item2" *ngFor="let projectTitle of projectInfo.title">
  <img class="center" src="https://natureconservancy-h.assetsadobe.com/is/image/content/dam/tnc/nature/en/photos/tnc_48980557.jpg?crop=961,0,1928,2571&wid=600&hei=800&scl=3.21375">
  <h5>{{projectTitle}}</h5>
  <p>{{ projectInfo.description }}</p>
</div>
相关问题