【问题标题】:Angular - *ngFor loop with indexAngular - 带索引的 *ngFor 循环
【发布时间】:2019-03-16 01:21:27
【问题描述】:

我对 Angular 很陌生,目前我正在学习 Angular 6,它是 Angular 的最新版本。

在这里,我正在尝试使用从 JSON 检索的文章来设计我的博客页面,并将它们显示在 2 列中,如下图所示:

标题旁边的数字是文章数组中文章的索引。很容易看出问题:从 1 开始的索引重复了两次。

这是我的代码,请详细说明为什么我错了以及如何解决。

博客服务:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class BlogService {

  constructor(private http: HttpClient) { }

  getArticleList() {
    return this.http.get('https://jsonplaceholder.typicode.com/posts');
  }
}

文章列表组件:

从'@angular/core'导入{组件,OnInit}; 从'../blog.service'导入{ BlogService };

@Component({
  selector: 'app-blog',
  templateUrl: './article-list.component.html',
  styleUrls: ['./article-list.component.css']
})
export class ArticleListComponent implements OnInit {
  articles: Object;

  constructor(private data: BlogService) { }

  ngOnInit() {
    this.data.getArticleList().subscribe(
      data => this.articles = data
    );
  }
}

HTML 文件:

<div class="article-list-page">
    <div class="container">
      <h3>This is blog page</h3>
      <p>The industry's top wizards, doctors, and other experts offer their best advice, research, how-tos, 
          and insights, all in the name of helping you level-up your SEO and online marketing skills. Looking for the YouMoz Blog? </p>
        <span *ngFor="let index of articles; index as i">
            <div style="display: table; border: 1px solid black">
                <div class="posts-left col-md-6" style="display: table-row;">
                    <a>{{ articles[i].title }} -- {{i}}</a>
                    <p>{{ articles[i].body }}</p>
                </div>
                <div class="posts-right col-md-6" style="display: table-row;">
                    <a>{{ articles[i + 1].title }} -- {{i + 1}}</a>
                    <p>{{ articles[i + 1].body }}</p>
                </div>
            </div>
        </span>
    </div>
</div>

【问题讨论】:

  • 如果你想显示所有文章,你不需要做{{articles[i].title }}...你应该做{{articles.title }}只有它们列出...而不是索引...您还可以显示 {{articles.id}}... 这是您数据中的 ID 字段

标签: html angular angular6


【解决方案1】:

TL;DR;只需在您的 HTML 文件中替换此块

发件人:

<div style="display: table; border: 1px solid black">
    <div class="posts-left col-md-6" style="display: table-row;">
        <a>{{ articles[i].title }} -- {{i}}</a>
        <p>{{ articles[i].body }}</p>
    </div>
    <div class="posts-right col-md-6" style="display: table-row;">
        <a>{{ articles[i + 1].title }} -- {{i + 1}}</a>
        <p>{{ articles[i + 1].body }}</p>
    </div>
</div>

收件人:(删除 4 行)

<div style="display: table; border: 1px solid black">
    <div class="posts-left col-md-6" style="display: table-row;">
        <a>{{ articles[i].title }} -- {{i}}</a>
        <p>{{ articles[i].body }}</p>
    </div>
</div>

从您的屏幕截图中,似乎只有0th 元素没有重复两次。根据您的 HTML,这是预期的,因为您要渲染两次。

您当前的模板

<span *ngFor="let index of articles; index as i">
    <div style="display: table; border: 1px solid black">
      <div class="posts-left col-md-6" style="display: table-row;">

          <!-- 1. Render the CURRENT 'article' -->
          <a>{{ articles[i].title }} -- {{i}}</a>
          <p>{{ articles[i].body }}</p>

      </div>
      <div class="posts-right col-md-6" style="display: table-row;">

          <!-- 2. Render the NEXT 'article' -->
          <a>{{ articles[i + 1].title }} -- {{i + 1}}</a>
          <p>{{ articles[i + 1].body }}</p>

      </div>
    </div>
</span>

以下是 Angular 如何渲染您的 articles 的步骤。

  1. 呈现第 0 个元素(您的模板呈现第 0 篇和第 1 篇文章)
  2. 呈现第一个元素(您的模板呈现第 1 篇和第 2 篇文章)
  3. 渲染第二个元素(您的模板渲染第二和第三篇文章)
  4. 等等..

如果您只想为每个元素渲染一次,只需这样做,

<div class="posts-left col-md-6" style="display: table-row;">
    <!-- 1. Render ONLY THE CURRENT 'article' -->
    <a>{{ articles[i].title }} -- {{i}}</a>
    <p>{{ articles[i].body }}</p>
</div>

注意:已经有帖子很好用了ngForHERE

【讨论】:

  • 有没有办法让这个循环像 Java 中的 for 循环一样工作?!因为我想并排显示文章,而不仅仅是 1 列中的文章列表。
  • 你能详细说明一下你的意思吗?如果您关心 UI,可以使用 css 对其进行样式设置。
  • 嗯,图片中的显示风格确实是我的意思,但问题是重复索引。有什么理由按这个顺序渲染我的文章?为什么不从循环体中计算的最后一个索引开始?
  • @TrungBún 你根本没看我的回答吗?但是,我已经更新了我的答案。看看TL;DR;
  • @TrungBún 它确实记得你的最后一个索引。但是你要渲染两次!!
【解决方案2】:

创建一个偶数索引数组

this.indexes = data.reduce((indexes, _, i) => i % 2 ? indexes : [...indexes, i], []);

在您看来,您可以仅对偶数索引进行 ngFor

<span *ngFor="let index of indexes">

【讨论】:

    【解决方案3】:

    与其使用表格并尝试以这种方式应用索引,不如使用 CSS。例如:

    在我的 component.ts 中:

    numArray=[100,200,300,400,500,600,700,800];
    

    在我看来:

      <ul>
        <li *ngFor="let n of numArray; index as i">{{n}}, Index is {{i}}</li>
      </ul>
    

    在css中:

    ul{
      width:400px;
    }
    li{
      float: left;
      list-style: none;
      width:150px;
      margin: 0px;
    }
    li:nth-child(even){
      margin-right: 0px;
    }
    

    这将给出如下输出:

    您可以修改我给出的示例以满足您的需要。

    【讨论】:

      猜你喜欢
      • 2017-11-01
      • 2019-02-12
      • 2017-10-30
      • 1970-01-01
      • 2020-10-25
      • 1970-01-01
      • 2018-02-10
      • 1970-01-01
      • 2013-02-15
      相关资源
      最近更新 更多