簡體   English   中英

如何在Angular中以NgFor為基礎構建內部NgFor

[英]How to base an inner NgFor on the outter NgFor in Angular

我正在嘗試在我的Angular應用程序中顯示對話列表,然后在每個對話標題下顯示各種對話中包含的消息。

這是我最新的代碼 -

HTML:

<div
   class="card"
   style="width: 18rem;"
   *ngFor="let conversation of myConversations"
>
<div class="card-body">
    <h5 class="card-title">{{ conversation.conversationTitle }}</h5>
    <h6 class="card-subtitle mb-2 text-muted">
       Conversation ID: {{ conversation.conversationId }}
    </h6>
    <p *ngFor="let message of myConversationMessages" class="card-text">
       {{ message.messageText }}
    </p>
</div>

TS:

myConversations: IConversation[] = [];
myConversationMessage: IConversationMessages = {
conversationId: 0,
messageId: 0,
messageText: ''
}; 
myConversationMessages: IConversationMessages[] = [];
constructor(private conversationService: ConversationService) {}

ngOnInit() {
this.conversationService.getConversations().subscribe(conversations => {
  this.myConversations = conversations;
  this.displayMessages();
});
}

displayMessages() {
for (let i of this.myConversations) {
  for (let j of i.messages) {
    this.myConversationMessages.push({
        conversationId: i.conversationId,
        messageId: j.messageId,
        messageText: j.messageText
    });
  }
}
console.log(this.myConversationMessages);
}

這是我目前能夠顯示的內容:

在此輸入圖像描述

每個對話都有自己的卡片,但是無論他們連接到哪個對話,所有對話都會重復這些消息。

我想我需要對內部ngFor進行一些更改,但我不確定要做出哪些更改。 有關需要進行哪些更改的任何想法? 謝謝!

此外,這是相關的JSON:

[
  {
    "conversationId": 1,
    "conversationTitle": "My first convo",
    "messages": [
      {
        "messageId": 1,
        "messageText": "Hi"
      },
      {
        "messageId": 2,
        "messageText": "Hello"
      }
    ]
  },
  {
    "conversationId": 2,
    "conversationTitle": "My second convo",
    "messages": [
      {
        "messageId": 1,
        "messageText": "test"
      },
      {
        "messageId": 2,
        "messageText": "testing"
      }
    ]
  }
]

根據您提供的JSON,您應該能夠在*ngfor使用*ngfor來閱讀消息。 我已經刪除了一些元素,但以下內容應該可以為您提供所需的結果。 基於問題中的JSON。

<div class="card" style="width: 18rem;" *ngFor="let conversation of myConversations">
    <div class="card-body">
        <h5 class="card-title">
            {{ conversation.conversationTitle }}
        </h5>

        <h6 class="card-subtitle mb-2 text-muted"> Conversation ID:
            {{ conversation.conversationId }}
        </h6>

        <div *ngFor="let message of conversation.messages" class="card-text">
            <span>
                {{ message.messageText }}
            </span>
        </div>
    </div>
</div>

如果JSON是最初的myConversations那么您將不需要對該數據執行任何其他操作,因為它已經足夠使用了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM