Angular - \*ngFor 循环与索引

新手上路,请多包涵

我是 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’导入{Component,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>

原文由 Trung Bún 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 380
1 个回答

与其使用表格并尝试以这种方式应用索引,不如使用 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;
}

这将给出如下输出:

在此处输入图像描述

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

原文由 codingsplash 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏