Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

angular - How to ngFor on multiple types of components using ngComponentOutlet?

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...