如何在Angular中的外部NgFor上建立内部NgFor

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

我正在尝试在我的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);
}

这是我目前能够显示的内容:

enter image description here

每个对话都有自己的卡片,但是无论他们连接到哪个对话,所有对话都会重复这些消息。

我想我需要对内部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 angular ngfor
1个回答
5
投票

基于您提供的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,那么您将不再需要对该数据执行任何操作,因为它已经足够使用了。

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