首页 > 解决方案 > 如何使用 Angular 仅选择第一个元素?“Django 后端”

问题描述

所以正如我在标题中提到的,我让 django 在后端工作,将我的数据发送到 angular,我有一个评论列表我只想在 html 页面中显示我列表的第一个元素我在尝试 limitTo 时遇到了这个错误

Failed to compile.

src/app/app.component.html:8:3 - error TS2551: Property 'comment' does not exist on type ' 
AppComponent'. Did you mean 'comments'?

8 {{comment.author}}
~~~~~~~

src/app/app.component.ts:6:16
6   templateUrl: './app.component.html',
                 ~~~~~~~~~~~~~~~~~~~~~~
Error occurs in the template of component AppComponent.

这是我的 app.component.html :

<ul>
<li *ngFor="let topic of topics">
<h2> Hey  {{topic.author}}</h2>
</li>
<h2 ng-repeat="comment in comments | limitTo : 1">
{{comment.author}}
</h2>
</ul>

顺便说一句,*ngFor 完美地工作我只需要拿评论的第一个元素谢谢

标签: pythondjangoangulartypescript

解决方案


这是解决方案:

<ul>
<li *ngFor="let topic of topics">
<h2> Hey  {{topic.author}}</h2>
 </li>

{{comments[0]["author"]}}
</h2>
</ul>

推荐阅读