如何创建 Angular 组件的多个实例?

How can I create multiple instances of an Angular Component?

我开始学习Angular,现在我正在用它来创建一个聊天界面。

主要部分将是一个以文本气泡形式显示来自用户和助手的消息的框,一个用户可以在其中键入将发送到聊天的文本的框,以及一个用于发送内容的按钮聊天框。

我为用户文本气泡创建了一个组件。我怎样才能做到这一点,以便在提交输入时创建 UserTextBubble 的新实例并将其附加到屏幕上的聊天对话框中?

我知道我可以创建一个数组并遍历它以在屏幕上显示一个列表,但如果可能的话我不想将对话的所有输入都保存在内存中。我希望能够将它插入屏幕上,然后将其留在那里。

您可以像对待任何其他 html 元素一样对待您的组件,并使用 NgFor 对其进行循环以提供任何必要的数据。

fake.component.html

<div>
  <your-component-selector-name *ngFor="let array of yourArry"></your-component-selector-name>
</div>

文档中有关组件交互的一些有用信息 https://angular.io/guide/component-interaction

您可以使用ViewContainerRef动态添加组件。

要实现此目的,您只需将 ng-template 添加到带有模板引用的组件 html 文件中。

<ng-template #chatContainer></ng-template>

然后在 *.component.ts 中使用 ViewContainerRef

UserTextBubbleComponent 添加到 ng-template

要从模板中获取 ViewContainerRef,您可以使用您在上一步中定义的 #chatContainer 通过 @ViewChild().

访问它
@ViewChild('chatContainer', {read: ViewContainerRef}) vc: ViewContainerRef;

您还需要 ComponentFactoryResolver,所以将其添加到 constructor()

constructor(private factory: ComponentFactoryResolver) {}

要将组件添加到 #chatContainer 您可以使用此方法

  addComponent(text) {
    const factory = this.factory.resolveComponentFactory(UserTextBubbleComponent);
    const componentRef = this.vc.createComponent(factory);
    (componentRef.instance).textToDisplay = text;
  }

此方法的作用是为 UserTextBubbleComponent 创建 ComponentFactoryResolver,这将允许您通过 createComponent.

创建它

最后一行在 UserTextBubbleComponent.

中,而不是 @Input()

为了能够像这样使用它,您还需要在组件内部定义 textToDisplay

所以在 UserTextBubbleComponent 里面添加 textToDisplay 它将是聊天气泡的值。

public textToDisplay: string;

您可能还需要将 UserTextBubbleComponent 添加到 entryComponents 数组。在 AppModule 内,在 imports

下添加
 @NgModule({
  imports:      [ BrowserModule, ...],
  declarations: [ AppComponent, UserTextBubbleComponent, ...],
  bootstrap:    [ AppComponent],
  entryComponents: [UserTextBubbleComponent, ...]
})
export class AppModule { }

我也做了一个example