Home > Software design >  Angular 13 - How can I check array length before rendering using <mat-accordion> and <mat-e
Angular 13 - How can I check array length before rendering using <mat-accordion> and <mat-e

Time:02-18

I had try this code but it is not work:

TS:

import { Component } from '@angular/core';

@Component({
  selector: 'app-post-list',
  templateUrl: 'post-list.component.html',
  styleUrls: ['post-list.component.css'],
})
export class PostListComponent {

  posts = [];
}

HTML:

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

<p *ngIf="posts.length == 0">No posts</p>

The error:

Initial Chunk Files | Names | Raw Size main.js | main | 20.68 kB | runtime.js | runtime | 6.52 kB |

3 unchanged chunks

Build at: 2022-02-17T12:49:32.171Z - Hash: 942ee67818541d4c - Time: 170ms

Error: src/app/posts/post-list/post-list.component.html:6:15 - error TS2339: Property 'title' does not exist on type 'never'.

6 {{ post.title }} ~~~~~

src/app/posts/post-list/post-list.component.ts:5:16 5 templateUrl: 'post-list.component.html', ~~~~~~~~~~~~~~~~~~~~~~~~~~ Error occurs in the template of component PostListComponent.

Error: src/app/posts/post-list/post-list.component.html:8:16 - error TS2339: Property 'content' does not exist on type 'never'.

8

{{ post.content }}

~~~~~~~

src/app/posts/post-list/post-list.component.ts:5:16 5 templateUrl: 'post-list.component.html', ~~~~~~~~~~~~~~~~~~~~~~~~~~ Error occurs in the template of component PostListComponent.

CodePudding user response:

You can disable type checking in template like explained here :- https://angular.io/guide/template-typecheck#disabling-type-checking-using-any

Your source code would look like :-

<mat-accordion multi="true" *ngIf="posts.length > 0">
  <mat-expansion-panel *ngFor="let post of posts">
    <mat-expansion-panel-header>
      {{ $any(post).title }}
    </mat-expansion-panel-header>
    <p>{{ $any(post).content }}</p>
  </mat-expansion-panel>
</mat-accordion>

<p *ngIf="posts.length == 0">No posts</p>
  • Related