gavard.e
gavard.e

Reputation: 142

How to render subclass component in angular 2?

I have a main class, Module which is extended by many subclasses such as TextOnlyModule or ImageOnlyModule.

I have a component, Preview, that contains a Module Array.

Here's a little diagram :

enter image description here

I'd like, in preview template, to render each Module with its subclass template. In the following example, modules is an Array of Module, and i'd like something to render each module with its template without calling directly each selector as I don't know the Module subtype.

<div *NgFor="#module in modules">
    {{module}}
</div>

Is there any way to do this ?

Thanks.

Upvotes: 1

Views: 804

Answers (1)

Thierry Templier
Thierry Templier

Reputation: 202196

Perhaps you could do that programmatically within the Preview component using the DynamicComponentLoader class:

@Component({
  (...)
  template: `
    <div #someContainer></div>
  `
})
export class Preview {
  constructor(dcl:DynamicComponentLoader,eltRef:ElementRef) {
    this.modules = ...

    this.modules.forEach((module) => {
      dcl.loadIntoLocation(module, eltRef, 'someContainer');
    });
  }
}

Here is some plunkr: https://plnkr.co/edit/UtVpvnTHPiR675lztOcQ?p=preview.

Hope it helps you, Thierry

Upvotes: 1

Related Questions