How to ngFor on multiple types of components using ngComponentOutlet?
Asked Answered
H

1

9

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

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

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

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!

Horologist answered 17/7, 2017 at 7:48 Comment(1)
put both in one array of data, using the controller or view.Wrack
F
13

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>

Array object should be as

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

},
{
  name: 'user'
  component: usersComponent

},
{
  name: 'slider'
  component: sliderComponent

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

]

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

entryComponents: [AlertDangerComponent, AlertSuccessComponent, usersComponent, sliderComponent ]

LIVE DEMO

Fiasco answered 17/7, 2017 at 8:7 Comment(6)
@mayur Thank you. :) :)Fiasco
is it somehow possible to pass data into "*ngComponentOutlet"?Hylton
@Benjamin yes it is possibleFiasco
Are sliderComponent and usersComponent types or instances? I'm asking because they are lower-casePismire
Yes they are component themselves @SimonFiasco
@Fiasco how to pass data into *ngComponentOutlet?Ashjian

© 2022 - 2024 — McMap. All rights reserved.