【问题标题】:How to base an inner NgFor on the outter NgFor in Angular如何在 Angular 中将内部 NgFor 建立在外部 NgFor 的基础上
【发布时间】:2019-08-10 12:39:35
【问题描述】:

我正在尝试在我的 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 angular ngfor


    【解决方案1】:

    根据您提供的 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,那么您不需要对这些数据做更多的事情,因为它已经足够使用了。

    【讨论】:

      猜你喜欢
      • 2018-09-29
      • 1970-01-01
      • 2016-07-19
      • 1970-01-01
      • 2018-09-20
      • 2018-01-11
      • 2018-08-13
      相关资源
      最近更新 更多