如何在 Angular 中基于外部 NgFor 建立内部 NgFor

How to base an inner NgFor on the outter NgFor in Angular

我正在尝试在我的 Angular 应用程序中显示对话列表,然后在每个 对话标题 下方显示这些不同对话中包含的消息。 =15=]

这是我最新的代码 -

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 那么您将不需要对该数据做任何更多的事情,因为它已经足够使用了。