How to use ngFor for several types of components using ngComponentOutlet?

I have a whatsapp-like chat case with many types of messages that need to be displayed in different ways.

Each has its own component, such as TextMessageComponent, FileMessageComponentetc.

I would like to be able to ngForonce on my message array without the need ngIffor types.

I heard what ngComponentOutletmight be the solution, but it was hard to implement it.

Any suggestions, mini-demos or anything you find useful will be highly appreciated!

+4
source share
1 answer

Having an object property 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>

The array object should be like

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

},
{
  name: 'user'
  component: usersComponent

},
{
  name: 'slider'
  component: sliderComponent

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

]

, AppModule

entryComponents: [AlertDangerComponent, AlertSuccessComponent, usersComponent, sliderComponent ]

LIVE DEMO

+7

Source: https://habr.com/ru/post/1680384/


All Articles