我是 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 许可协议
与其使用表格并尝试以这种方式应用索引,不如使用 CSS。例如:
在我的 component.ts 中:
在我看来:
在 CSS 中:
这将给出如下输出:
您可以修改我给出的示例以满足您的需要。