1

I have a list

*ngFor="let h of list"

Depending on the type of the item "h.type" I want to use a different component to display details. How do I load the component?

1
  • 1
    You could do it with an NgIF or NgSwitch Commented Mar 16, 2018 at 15:02

3 Answers 3

1

Here is how you could do it with an NgSwitch:

<div *ngFor="let h of list" [ngSwitch]="h.type">
  <ng-container *ngSwitchCase="'x'">
    <component-x>
  </ng-container>
  <ng-container *ngSwitchCase="'y'">
    <component-y>
  </ng-container>
</div>

You might be able to skip the ng-container but I haven't tested that:

<div *ngFor="let h of list" [ngSwitch]="h.type">
    <component-x  *ngSwitchCase="'x'">
    <component-y  *ngSwitchCase="'y'">
</div>
Sign up to request clarification or add additional context in comments.

Comments

0

You can use ng-template for that. E.g.

<div *ngFor="let h of list">
  <ng-container *ngIf="h.type === 'FIRST'">
    <ng-container *ngTemplateOutlet="firstTemplate"></ng-container>
  </ng-container>

  <ng-container *ngIf="h.type === 'SECOND'">
    <ng-container *ngTemplateOutlet="secondTemplate"></ng-container>
  </ng-container>
</div>

<!-- now define the two templates -->
<ng-template #firstTemplate>
  <my-first-component/>
</ng-template>
<ng-template #secondTemplate>
  <my-second-component/>
</ng-template>

2 Comments

Umm, what benefit do you get with switching the template? Why not ngIf on the components directly?
No idea, honestly. I've written this 3 years ago so I was proably heavily drilling into ng-template stuff. One thing I think it may be applicable is if you don't want to create a new component for that. But that doesn't make sense, when you look at the question. No idea.
0

You can accomplish this by using *ngIf And load components with their selectors directly in html.

<component1 *ngIf="h.type == ‘car’"></component1>
<component2 *ngIf="h.type == ‘truck’"></component2>

Component 1 is going to be displayed when h.type is car and component 2 is going to be displayed when h.type is truck.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.