You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular聊天功能实现:点击sidebar用户在右侧打开对应会话咨询

实现方案

核心思路

该场景属于典型的兄弟组件通信,Angular中可以通过「子组件传值给父组件,父组件再转发给另一个子组件」的方式实现,无需额外引入状态管理库,逻辑轻量完全匹配需求。

具体实现步骤

步骤1:修改父组件Chat的逻辑

首先更新父组件的TS文件,定义选中用户的存储变量和接收选中事件的方法:

// chat.component.ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-chat',
  templateUrl: './chat.component.html'
})
export class ChatComponent {
  // 存储当前选中的用户ID,可根据需求替换为完整的User对象
  selectedUserId?: string | number;

  // 接收sidebar子组件抛出的选中用户ID
  onUserSelect(userId: string | number) {
    this.selectedUserId = userId;
  }
}

再修改父组件模板,绑定事件监听和输入属性:

<!-- chat.component.html -->
<div class="container-fluid">
<div class="row">
    <div class="col-5">
        <!-- 监听sidebar子组件抛出的userSelected事件 -->
        <app-sidebar (userSelected)="onUserSelect($event)"></app-sidebar>
    </div>
    <div class="col-7">
        <!-- 把选中的用户ID传递给对话详情子组件 -->
        <app-conversation-detail [userId]="selectedUserId"></app-conversation-detail>
    </div>
</div>
</div>

步骤2:修改Sidebar子组件,抛出选中用户事件

更新sidebar组件的TS文件,定义输出事件和用户列表数据:

// sidebar.component.ts
import { Component, Output, EventEmitter } from '@angular/core';
// 可根据实际业务替换为你的User类型定义
interface User {
  id: string | number;
  name: string;
  avatar: string;
}

@Component({
  selector: 'app-sidebar',
  templateUrl: './sidebar.component.html'
})
export class SidebarComponent {
  // 输出事件,用于把选中的用户ID传给父组件
  @Output() userSelected = new EventEmitter<string | number>();

  // 模拟用户列表,可替换为真实接口返回的数据
  userList: User[] = [
    {id: '1', name: '张三', avatar: 'xxx'},
    {id: '2', name: '李四', avatar: 'xxx'}
  ]
}

修改sidebar模板,给每个用户项绑定点击触发事件:

<!-- sidebar.component.html -->
<div class="user-list">
  <div 
    class="user-item" 
    *ngFor="let user of userList"
    (click)="userSelected.emit(user.id)"
  >
    <img [src]="user.avatar" alt="用户头像">
    <span>{{user.name}}</span>
  </div>
</div>

步骤3:修改ConversationDetail子组件,拉取对应聊天内容

更新对话详情组件的TS文件,接收用户ID并监听变化拉取聊天记录:

// conversation-detail.component.ts
import { Component, Input, OnChanges, SimpleChanges } from '@angular/core';
// 可根据实际业务替换为你的聊天消息类型定义
interface ChatMessage {
  id: string;
  content: string;
  sendTime: Date;
  isSelf: boolean;
}

@Component({
  selector: 'app-conversation-detail',
  templateUrl: './conversation-detail.component.html'
})
export class ConversationDetailComponent implements OnChanges {
  // 接收父组件传过来的选中用户ID
  @Input() userId?: string | number;

  chatMessageList: ChatMessage[] = [];

  // 监听用户ID变化,切换聊天对象时自动拉取对应记录
  ngOnChanges(changes: SimpleChanges): void {
    if (changes['userId'] && this.userId) {
      this.loadChatHistory(this.userId);
    }
  }

  // 拉取聊天记录的方法,替换为你的真实接口请求即可
  private loadChatHistory(userId: string | number) {
    console.log('拉取用户ID为', userId, '的聊天记录');
    // 模拟接口返回数据
    this.chatMessageList = [
      {id: 'msg1', content: '你好', sendTime: new Date(), isSelf: false},
      {id: 'msg2', content: '请问有什么事?', sendTime: new Date(), isSelf: true}
    ]
  }
}

对话详情的模板直接遍历chatMessageList渲染聊天消息即可,无需额外修改逻辑。

可选优化:侧边栏选中用户高亮

如果需要给当前选中的用户添加高亮样式,只需做两处修改:

  1. 父组件给sidebar传递选中的用户ID:
<app-sidebar 
  (userSelected)="onUserSelect($event)"
  [selectedUserId]="selectedUserId"
></app-sidebar>
  1. sidebar组件新增输入属性接收选中ID,模板判断添加高亮类:
// sidebar.component.ts 新增输入属性
@Input() selectedUserId?: string | number;
<!-- sidebar.component.html 给用户项绑定动态class -->
<div 
  class="user-item" 
  *ngFor="let user of userList"
  (click)="userSelected.emit(user.id)"
  [class.active]="user.id === selectedUserId"
>

自行定义.active类的样式即可实现选中高亮效果。

内容的提问来源于stack exchange,提问作者abhas01

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 07:27:04