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

如何在Angular中通过TypeScript动态添加ChatBubble组件

Angular 动态生成ChatBubble组件并绑定消息方案

步骤1:修改ChatBubbleComponent,暴露可输入属性

原组件的text是普通属性,需添加@Input()装饰器才能接收外部传入的值:

@Component({
  selector: 'app-chat-bubble',
  standalone: true,
  imports: [],
  templateUrl: './chat-bubble.component.html',
  styleUrl: './chat-bubble.component.scss'
})
export class ChatBubbleComponent{
  @Input() text: string = ''; // 添加@Input()允许外部传值
  @HostBinding("class") @Input() textType: 'send' | 'receive' = 'send';
}

同时确保ChatBubble的模板渲染text内容(示例chat-bubble.component.html):

<div class="chat-bubble">
  {{ text }}
</div>

步骤2:改造ChatbotComponent实现动态创建

2.1 模板中添加容器引用

在Chatbot的模板里,给存放气泡的div加上模板引用变量#chatContainer:

<!-- chatbot.component.html -->
<div #chatContainer class="chat-container"></div>

<!-- 保留原有表单 -->
<form [formGroup]="chat" (ngSubmit)="onSubmitChat()">
  <input formControlName="message" placeholder="输入消息">
  <button type="submit">发送</button>
</form>

2.2 组件类中实现动态创建逻辑

导入所需API,通过ViewChild获取容器引用,在表单提交时生成ChatBubble实例并绑定消息:

import { Component, ViewChild, ViewContainerRef, ComponentRef } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';
import { ChatBubbleComponent } from './chat-bubble.component';

@Component({
  selector: 'app-chatbot',
  standalone: true,
  imports: [ContentCardComponent, ButtonComponent, InputSelectComponent, ReactiveFormsModule, ChatBubbleComponent],
  templateUrl: './chatbot.component.html',
  styleUrl: './chatbot.component.scss'
})
export class ChatbotComponent{
  options = new FormGroup({
    'style': new FormControl('short'),
    'model': new FormControl('open-ai'),
    'argument': new FormControl('delibere'),
  })

  chat = new FormGroup({
    'message': new FormControl('')
  });

  // 获取存放气泡的容器引用
  @ViewChild('chatContainer', { read: ViewContainerRef }) chatContainer!: ViewContainerRef;

  onSubmitOptions() {
    console.log(this.options.value);
  }

  onSubmitChat() {
    const message = this.chat.get('message')?.value?.trim();
    if (!message) return;

    // 动态创建ChatBubble组件实例
    const bubbleRef: ComponentRef<ChatBubbleComponent> = this.chatContainer.createComponent(ChatBubbleComponent);
    // 绑定消息和类型
    bubbleRef.instance.text = message;
    bubbleRef.instance.textType = 'send'; // 可根据需求切换为'receive'

    // 清空输入框
    this.chat.get('message')?.setValue('');
  }
}

关键说明

  • ViewContainerRef.createComponent()是Angular 14+推荐的动态组件创建方式,替代了已废弃的ComponentFactoryResolver。
  • 通过组件实例的instance属性直接设置输入属性,无需额外绑定逻辑。
  • 若需保留聊天记录,可将生成的组件引用存入数组,方便后续管理(如删除、滚动定位)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 04:42:11