Conditionally choose Angular html component dependent on the Objects Type/Class

Viewed 22

I have an array of two different types

events: Array<Appointment | SlotBlock>;
appointments: Array<Appointment>;
slotBlocks: Array<SlotBlock>;

i would like to iterate through events with *ngFor and render the correct component:

<div *ngFor="let event of events">
    <app-appointment-item *ngIf="typeOf(event) === Appointment" [event]="event">
    </app-appointment-item>
    <app-slotBlock-item *ngIf="typeOf(event) === SlotBlock" [event]="event">
    </app-slotBlock-item>
</div>

how to achieve that in Angular13/TS? I tried to do something like this.

isAppointment(val : any): val is Appointment{
    return (val as Appointment) !== undefined;
}

enter code here
// appointment.page.html
<ion-list *ngIf="events && events.length" class="ion-no-padding">
    <div *ngIf="isAppointment(event)" *ngFor="let event of events">
        <app-appointment-item *ngIf="isAppointment(event)" [event]="event">
        </app-appointment-item>
        .
        .
        .
     </div>
</ion-list>

but it returns always true. Does it make sense to check for the Objects type or is there a better solution?

0 Answers
Related