遍历打字稿中的对象数组并以html显示

问题描述 投票:0回答:1

我对Angle 7相当陌生,我有一个类似的对象。

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"
               }
           }]
       }
   } 
}

在视图中,我有3个部分来显示数组中的每个项目。

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

我想知道是否,1.我需要在视图中使用* ngFor来遍历数组。如果是这样,我如何在视图中使用索引来仅显示列表中的特定项目。2.如果我要遍历组件中的数组,请将其分配给单独的变量并在视图中使用它。例如:

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

但是我收到一个错误,属性'pageContent'在类型'Entry'上不存在。

有人可以帮我解决这个问题。谢谢

typescript angular7
1个回答
0
投票

*ngFor是理想的解决方案,因为您只需编写一次模板。我已经根据您的数据在stackblitz中创建了exmaple

© www.soinside.com 2019 - 2024. All rights reserved.