Search code examples
typescriptangular7

Iterate over array of Objects in typescript and display in html


I am fairly new to angular 7 and I have an object like this.

this.data = {
   title:"mypage",
   pageContent:{
       fields:{
           history:[{
               sys:{},
               fields:{
                 title:"my book",
                 description:"my description"
               }
           },

           {
              sys:{},
               fields:{
                 title:"book1",
                 subtitle:"description1"
               }
           },
            {
              sys:{},
               fields:{
                 title:"book2",
                 subtitle:"description3"
               }
           }]
       }
   } 
}

In the view, I have 3 sections to display each item in the array.

<div class="row">

      <div class="row">
      <!-- Display first item in the array -->
       <h3 class="text-center">{{data.fields.title}}</h3>
       <p class="our-history-text text-center">{{data.fields.description}}</p>
       </div>
       <!-- Second item in the array -->
       <div class="our-history-text-small" [innerHTML]="data.fields.subtitle | markdownToHtml" spaLinkTransformer></div> 
        <!-- Third item in the array -->
     <div class="our-history-text-small" [innerHTML]="data.fields.subtitle | markdownToHtml" spaLinkTransformer></div> 

</div>

I was wondering if, 1. I need to use *ngFor in the view to iterate over the array. If so, how can I use index in the view to just display specific items in the list. 2. If I should loop through the array in component, assign it to separate variables and use it in view. Eg:

myHistory: Entry<any>;
this.myservice.fetchAll(locale)
.then(entries => {
    this.myPage = entries.fields;
    this.myHistory = this.myHistory.pageContent.fields.history[0];
}

But I get an error Property 'pageContent' does not exist on type 'Entry'.

Could someone help me with the solution. Thanks


Solution

  • You need add ngFor to first div class row

    <div class="row" *ngFor="let data of data.pageContent.fields.history">
    
        <div class="row">
            <!-- Display first item in the array -->
            <h3 class="text-center">{{data.fields.title}}</h3>
            <p class="our-history-text text-center">{{data.fields.description}}</p>
        </div>
        <!-- Second item in the array -->
        <div class="our-history-text-small" [innerHTML]="data.fields.subtitle" spaLinkTransformer></div>
        <!-- Third item in the array -->
        <div class="our-history-text-small" [innerHTML]="data.fields.subtitle" spaLinkTransformer></div>
    
    </div>
    

    With Property 'pageContent' does not exist on type 'Entry' error, you need check Entry class defined.

    Stackbliz demo code: https://stackblitz.com/edit/angular-exrzwf