简体   繁体   中英

Why do I get 'Failed to compile error' in angular12 after looping an empty array?

I used angular material to create an accordion that suppose to display several posts:

  <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> 

In my.ts file I loop over posts array and everything works fine as long as it contains the post objects

 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'},
 ];

As soon as I empty the posts array in order to see the 'P' tag with 'No posts added yet' and than try to loop over it I get 'failed to compile error' even though I check beforehand that the array length is greater than 0. What am I missing?

Maybe you have to check if posts exists before:

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

can you reframe your question, not sure what you are trying to say exactly, I have replicated your code and it's working, check here - LiveDemo

Apparently I needed to initialized the posts[].

Like so: posts: { title: string; content: string }[] = [];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM