繁体   English   中英

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

[英]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 ,使用ViewContainerRefUserTextBubbleComponent添加到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创建它。

最后一行是存在的,而不是一些@Input()的内部UserTextBubbleComponent

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

所以加textToDisplay的内部UserTextBubbleComponent这将是聊天泡泡的价值。

public textToDisplay: string;

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

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

我也做了一个例子

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM