I know that there are many similar questions, and almost all of them end with the DynamicComponentLoader responder, but still, I think that the use case described below is so simple and common (IMO) that the solution with Angular 2 should be straightforward.
Usage example
I have an array of news with a type property that describes what this element is.
var items = [ { id: 1, type: 'text', data: {} }, { id: 2, type: 'text', data: {} }, { id: 3, type: 'text-two-columns', data: {} }, { id: 4, type: 'image-text', data: {} }, { id: 5, type: 'image', data: {} }, { id: 6, type: 'twitter', data: {} }, { id: 7, type: 'text', data: {} } ]
Each other type has a different view and a completely different logic. In other words, each type has its own angular2 Component .
Thus, the abstract code I'm trying to achieve is:
<div *ngFor="let item of items"> <item-{{item.type}} [data]="item.data"></item-{{item.type}}> </div>
Of course, this will not work.
Possible Solution # 1
<div *ngFor="let item of items"> <item-text *ngIf="item.type === 'text'" [data]="item.data"></item-text> <item-image *ngIf="item.type === 'image'" [data]="item.data"></item-image> ... </div>
I don't like this solution, not only because it looks ugly, and I have to include this line every time I add a new type, but I wonder if this solution is good in terms of performance? I mean, if I have 10,000 different types and only 3 elements to display. Thus, angular2 will have to be removed from the DOM 9,999 tags and only one should be left for each of the 3 elements (3 * 9999 remove operations).
Possible Solution # 2
<div *ngFor="let item of items"> <dynamic-component-loader [item]="item"></dynamic-component-loader> </div>
At the moment, I donโt remember how DynamicComponentLoader works (I tried this for a long time in a similar problem in angular2 alpha). But, as I recall, the code looks like a hack to me .. For such a general task? ..
Angular 1.x thinking
I don't know what I'm doing wrong, maybe the problem is what I still think in Angular 1 ? Using it, I would use ngInclude or a custom directive with a template function.
Do you guys have other solutions how to do this? Don't stick to my two possible solutions, maybe I need to think out of the box and solve this problem completely in different parts of my application. I'm confused. Thanks:)
EDIT: another example in the real world
Let's say your task is to write Facebook using Angular 2. I think you would run into the same problem trying to display a news feed. Each news item has a type ( text , event , ads , ..)