1

I want to render in the same page multiple blocs that can be of multiple type, for example an event, a location, a book, etc..

I defined an interface for this, that I called a Bloc. And multiple extensions of this interface.

export interface Bloc {
}

export interface BlocBook extends Bloc {
  name: string;
  image: string;
}

export interface BlocLocation extends Bloc {
  name: string;
  image: string;
}

export interface BlocEvent extends Bloc {
  name: string;
  location: Location;
  image: string;
}

The view must deal with Bloc[] and process them with a *ngFor.

I populate the array as follow :

for (let event of resp['events']){
   var b = <BlocEvent>{
      name: event.name,
      image: event.location.image,
    };
}

But the thing is that the layout depends on the type of the bloc. If it is an event I must display some information, if it is a book I must display other information.

For exemple, the routerLink to go to the detail page will not be the same. Or the background color of the bootstrap card.

All I have as of now is the @Input variable.

import { Component, OnInit, Input } from '@angular/core';
import { Bloc } from '../../../models/bloc';

@Component({
  selector: 'app-bloc',
  templateUrl: './bloc.component.html',
  styleUrls: ['./bloc.component.css']
})
export class BlocComponent implements OnInit {
  @Input() bloc: Bloc;

  constructor() { }

  ngOnInit() {
  }

}

How can I acheive this please ? Should I play with multiple *ngIf or is there a better way to do this ?

Liam
  • 27,717
  • 28
  • 128
  • 190
fallais
  • 577
  • 1
  • 8
  • 32
  • Does this answer your question? [Get an object's class name at runtime](https://stackoverflow.com/questions/13613524/get-an-objects-class-name-at-runtime) – Liam Jan 29 '20 at 09:00
  • @Liam : hum not really, I mean, I do not see how it could help me because the conditional rendering should be performed on the template no ? – fallais Jan 29 '20 at 09:08
  • I guess it's a starting point for you. That gives you the mechanism to decide if it's a `book` or and `event`. The rest is just using [ngif](https://malcoded.com/posts/angular-ngif-else/) – Liam Jan 29 '20 at 09:57
  • I will give it a try thanks – fallais Jan 29 '20 at 10:09
  • You could use [ngSwitch] instead of multiple *ngIfs – Ambrus Tóth Jun 10 '21 at 13:21

0 Answers0