首页 > 解决方案 > 为什么在循环一个空数组后在 angular12 中出现“无法编译错误”?

问题描述

我使用有角度的材料创建了一个手风琴,它应该显示几个帖子:

  <mat-accordion multi="true" *ngIf="posts.length > 0">
   <mat-expansion-panel *ngFor="let post of posts">
   <mat-expansion-panel-header>
   <mat-panel-title> {{ post.title }} </mat-panel-title>
   </mat-expansion-panel-header>
     <p>{{ post.content }}</p>
   </mat-expansion-panel>
  </mat-accordion>
  <p class="mat-body-1" *ngIf="posts.length === 0">No posts added 
   yet</p> 

在我的 .ts 文件中,我遍历了帖子数组,只要它包含帖子对象,一切都可以正常工作

 posts = [{ title: 'first post', content: 'this is the 1 post'}, { 
 title: 'second post', content: 'this is the 2 post' },
 { title: 'third post', content: 'this is the 3 post'},
 ];

一旦我清空帖子数组以查看带有“尚未添加帖子”的“P”标签,然后尝试循环遍历它,即使我事先检查数组长度是否更大,我也会得到“编译失败错误”比 0. 我错过了什么?

标签: javascriptangulartypescript

解决方案


也许您必须检查之前是否存在帖子:

*ngIf="posts && posts.length > 0">

推荐阅读