如何使用ngComponentOutlet对多种类型的组件进行ngFor? [英] How to ngFor on multiple types of components using ngComponentOutlet?

查看:104
本文介绍了如何使用ngComponentOutlet对多种类型的组件进行ngFor?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类似于whatsapp的聊天案例,其中许多类型的消息需要以不同的方式显示.

I've got a whatsapp-like chat case of many types of messages that are needed to be displayed differently.

每个都有自己的组件,例如TextMessageComponentFileMessageComponent等.

Each has its' own component such as TextMessageComponent, FileMessageComponent, etc..

我希望能够对消息数组进行一次ngFor,而不必对类型进行ngIf.

I'd like to be able to ngFor once on my array of messages without having to ngIf over the types.

我听说ngComponentOutlet可能是解决方案,但发现很难实现.

I've heard ngComponentOutlet might be the solution but found it hard to implement..

任何建议,迷你演示或您发现有用的任何东西,将不胜感激!

Any suggestions, a mini demo or anything you find useful would be highly appreciated!

推荐答案

在对象上具有属性应该对您有帮助

Having a property on the object should help you

<div *ngFor="let item of items"  style="border: solid 1px; padding: 20px;margin: 20px;">
      <span style="color:red"> {{item.name}} </span>
      <ng-container *ngComponentOutlet="item.component"><ng-container>
  <br>
</div>

数组对象应为

items:Array<any> = [
{
  name: 'slider'
  component: sliderComponent

},
{
  name: 'user'
  component: usersComponent

},
{
  name: 'slider'
  component: sliderComponent

},
{
  name: 'alert danger'
  component: AlertDangerComponent
}

]

通过在AppModule中使用它们来确保已加载所有组件

Ensure that all the components are loaded by using them in the AppModule

entryComponents: [AlertDangerComponent, AlertSuccessComponent, usersComponent, sliderComponent ]

实时演示

LIVE DEMO

这篇关于如何使用ngComponentOutlet对多种类型的组件进行ngFor?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆