简体   繁体   中英

Angular component, different content depending on Element

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?

You can use ng-template for that. Eg

<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>

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.

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM