![](/img/trans.png)
[英]How to programmatically dynamically create multiple independent instances of component in angular2?
[英]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
创建它。
最后一行是存在的,而不是一些@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.